括號「[ ]」可以放在變數名稱的前面或後面
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class CH009 { public static void main(String args[]) throws IOException { int arr1[] = new int [ 10 ]; // 宣告10個位置的陣列 int [] arr2; // 若不知道陣列需要多少位置時,可以不宣告長度 arr2 = new int [ 10 ]; // 待程式執行過後或參數帶入後,才宣告陣列長度 } } |
一維陣列
結構最簡單,最容易解的陣列形態。如果已經知道陣列中要放的資料,也可以直接初始陣列內容。1 2 3 4 5 6 7 8 9 | public class CH010 { public static void main(String args[]) throws IOException { String str [] = { "Air" , "Buy" , "Cute" , "Eat" , "Fail" }; } } |
已知內容可以用大括號區塊批次賦值,也可以用索引的方式逐一賦值。
取得陣列中的資料是以「索引」,從「[ ]」內的數字對應出位置中儲存的值。
1 | System.out.println(str[ 1 ]); |
陣列索引位置從「0 」開始,「0」在電腦世界是一切的起點。
替換陣列中的資料也是以「索引」,從「[ ]」內的數字對應位置換掉儲存的值。
1 2 3 | str[ 1 ]= "ball" ; System.out.println(str[ 1 ]); |
索引位置沒放東西,去呼叫會出現 Null Pointer exception ...
索引位置沒建立,去放東西會出現 Index out of bound exception ...
二維與多維陣列
多維陣列使用「多個索引」來指定存取陣列中的元素,其宣告方式與一維陣列相同。1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class CH011 { public static void main(String args[]) throws IOException { String str [][] = { { "A" , "B" , "C" , "D" , "E" }, { "甲" , "乙" , "丙" , "丁" , "戊" }, { "1" , "2" , "3" , "4" , "5" } }; str[ 0 ][ 2 ]= "ball" ; System.out.println(str[ 0 ][ 2 ]); } } |
沒有留言:
張貼留言