java數組的使用


Java語言的數組索引是從0開始的,也就是說數組里的第一個元素的索引是0,第二個元素的索引是1,依次可以類推。

常見操作:

給數組元素賦值

數組名[索引] = 數組類型的值 ;

訪問數組元素

數組類型 變量 = 數組名[索引];

得到數組的長度

int len  = 數組名.length;     //length是數組的屬性

遍歷數組(備注:length 屬性和循環語句)

數組元素的索引范圍(0,長度—1)

 

Eg:判斷數組是否重復

package reviewDemo;

/**

 * 判斷數組是否重復

 */

public class Demo3 {

    public static void main(String[] args) {

        int []age = {1,2,3,4,5,6,5};

        for (int i = 0; i < age.length-1; i++) {//雙層循環,定住一個,再考慮下一個!

            for (int j = i+1; j < age.length; j++) {

                if(age[i] == age[j]){

                    System.out.println("有重復的!"+i+"  "+j);

                    break;

                }

            }

        }

    }

}

 

求最大值:

package reviewDemo;

 

public class Demo4 {

    public static void main(String[] args) {

        int age[] = new int[] { 12, 26, 3, 60, 55, 6, 48, 4, 98 };

        int max = age[0];

        for (int i = 0; i < age.length; i++) {

            if (max < age[i]) {

                max = age[i];

            }

        }

        System.out.println(max);

 

    }

}

 

經典用法:冒泡法排序

class Bubblesort

{

    public static void main(String args[])

    {

        int [] arr={5,1,6,4,2,8,9};

        bubble(arr);

        printarray(arr);

 

    }

    public static void bubble(int[] arr)

    {

        for (int i=0;i<arr.length-1 ;i++ )

        {

            for (int y=0;y<arr.length-i-1 ; y++) //讓每一次比較的元素減少,-1是為了防止數組角標越界;

            {

                if(arr[y]>arr[y+1])  //相鄰兩元素相比

                {

                    int temp = 0;

                    temp = arr[y];

                    arr[y] = arr[y+1] ;

                    arr[y+1] = temp;

                }

            }

        }

    }

    public static void printarray(int[] arr)

    {

 

        for (int i=0;i<arr.length ;i++ )

        {

            if(i!=arr.length-1)

            System.out.print(arr[i]+",");              

            else

                System.out.println(arr[i]);

        }

    }

 

}

//選擇排序

public class Demo6 {

    public static void main(String[] args) {

        int []age = {1,2,36,363,56,95,12,32,1232,3263};

       

        for (int i = 0; i < age.length; i++) {

            for (int j = i+1; j <= age.length-1; j++) {

                if(age[i] > age[j]){

                    int temp = age[i];

                    age[i] = age[j];

                    age[j] = temp;

                }

            }

        }

        System.out.println(Arrays.toString(age));

    }

}  

//輸出為:[1, 2, 12, 32, 36, 56, 95, 363, 1232, 3263]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM