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. ; } |
第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. ; } System.out. ; } |
執行結果:
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
可參考下表:
型態 | 初始值 |
byte | 0 |
short | 0 |
int | 0 |
long | 0L |
float | 0.0F |
double | 0.0D |
char | \u0000(空字元) |
boolean | false |
類別 | 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. ; } System.out. ; } |
如想new出二維陣列,也給初始值,那就:
1 2 3 4 | int[][] cords = new int[][] { {1, 2, 3}, {4, 5, 6} }; |
int cords[][] 這樣寫也可以
所以它的圖長這樣:
沒有留言:
張貼留言