2016/4/27

Java:陣列

本篇參考  http://openhome.cc/Gossip/Java/Array.html

for(int score : scores) {
    System.out.printf("學生分數:%d %n", score);
}


1
2
3
4


        int scores[] = {88, 81, 74, 68, 78, 76, 77, 85, 95, 93};
        for(int i = 0; i < scores.length; i++) {
            System.out.printf("學生分數:%d %n", scores[i]);
        }


第1行:宣告

第23行:利用for迴圈讀出陣列元素

執行結果:

學生分數:88
學生分數:81
學生分數:74
學生分數:68
學生分數:78
學生分數:76
學生分數:77
學生分數:85
學生分數:95
學生分數:93

for增強寫法

for(int score : scores) {
    System.out.printf("學生分數:%d %n", score);
}

score為變數與上面for迴圈執行結果一樣

設定值給陣列中某元素

scores[3] = 86;


二維陣列


1
2
3
4
5
6
7
8
9
10


        int cords[][] = {
            {1, 2, 3},
            {4, 5, 6}
        };
        for(int x = 0; x < cords.length; x++) {
            for(int y = 0; y < cords[x].length; y++) {
                System.out.printf("%2d", cords[x][y]);
            }
            System.out.println();
        }


執行結果:

1 2 3
4 5 6

操作陣列物件  http://openhome.cc/Gossip/Java/ArrayInstance.html

如不知元素值,但知道元素的數量,可這樣做:

int[] scores = new int[10];

new就是建立物件,一個陣列物件,而new出來每個元素索引會有預設值,所以:

int[] scores = new int[10];
System.out.println(scores[0]);

印出:0

可參考下表:

型態初始值
byte0
short0
int0
long0L
float0.0F
double0.0D
char\u0000(空字元)
booleanfalse
類別null

如想設定初始值可用java.util.Arrays的fill()方法

如想new陣列一併指定初始值,可這麼寫:

int[] scores = new int[] {88, 81, 74, 68, 78, 76, 77, 85, 95, 93};

而且不用給長度



二維陣列物件宣告:

int[][] cords = new int[2][3];

這是一個2*3的陣列,建立一個int[][]型態的物件,裡面有2個int[]型態索引,分別參考長度為3的一維陣列物件,如下圖:



試問,cords.length這樣是多少?答為2

意思是,取得cords參考的物件有幾個索引

那,cords[0].length?答為3

同理,cords[1].length?也為3

所以二維陣列的走訪,現在來看看應該更好懂了吧:


1
2
3
4
5
6


for(int x = 0; x < cords.length; x++) {
    for(int y = 0; y < cords[x].length; y++) {
        System.out.printf("%2d", cords[x][y]);
    }
    System.out.println();
}



如想new出二維陣列,也給初始值,那就:


1
2
3
4


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



int cords[][]  這樣寫也可以

所以它的圖長這樣:





沒有留言:

張貼留言