為什么要使用數組: 因為不使用數組計算多個變量的時候太繁瑣,不利於數據的處理。
-------- 數組也是一個變量,是存儲一組相同類型的變量
聲明一個變量就是在內存中划出一塊合適的空間
聲明一個數組就是在內存中划出一塊連續的空間
數組長度就是數組存放了多少個數,最大下標等於數組長度減一
數組中所有的元素必須屬於相同的數據類型
使用數組4步
1.申明數組:int[] a; 或者 int a[];
2.分配空間:a = new int[5];
3.賦值:a[0] = 8; a[1] = 5;
4.處理數據:a[2] = a[0]+a[1];
案例:
public class var { public static void main(String[] args) { int index[]; //申明 index = new int[5]; //分配空間 index[0] = 1;index[1] = 2;index[2] = 3;index[3] = 4;index[4] = 5; //賦值 for (int i = 0; i < index.length; i++) { System.out.println("第"+i+"個元素的值:"+index[i]); } } }
運行結果:
二維數組:使用數組4步
1.申明數組:int arr[][];或者 int[][] arr;
2.分配空間:arr = new int[5][5];
3.賦值:arr[0][0] = 1; arr[0][1] = 2; .......
4.處理數據:arr[1][0] = arr[0][0]+arr[0][1];
案例:
public class var { public static void main(String[] args) { int[][] index; //申明 index = new int[3][3]; //分配空間 //循環賦值 int num = 0; for (int i = 0; i < index.length ; i++) { for (int j = 0; j < index[0].length; j++) { index[i][j] = num++; } } //輸出 for (int i = 0; i < index.length ; i++) { for (int j = 0; j < index[0].length; j++) { System.out.print(index[i][j]+" "); } System.out.println(); } } }
運行結果:
----- 使用數組的常見錯誤
1、直接賦值的時候不需要寫長度 但是不賦值的話要寫長度, int[] scores = new int[];
2、數組下標越界異常 下標超過了數組長度減一的值