更新時間:2021-05-13 10:19:40 來源:動力節(jié)點 瀏覽1119次
數(shù)組指一組數(shù)據(jù)的集合,數(shù)組中的每個數(shù)據(jù)被稱作元素。
數(shù)組類型[] 數(shù)組名 = new 數(shù)組類型[元素個數(shù)或數(shù)組長度];
(注意:等號前面的[]里面不能寫任何東西)
也可以以下寫法:
數(shù)組類型[] 數(shù)組名 = {元素,元素,....};
用‘“數(shù)組名.length”的方式來獲得數(shù)組的長度,即元素的個數(shù)。
| 數(shù)組類型 | 默認初始化 |
|---|---|
| byte short int long | 0 |
| float double | 0.0 |
| char | 一個空字符(空格),即‘\u0000’ |
| boolean | false |
| 引用數(shù)據(jù)類型 | null,表示變量不引用任何對象 |
用for循環(huán):
public class ArrayDemo04 {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5 }; // 定義數(shù)組
// 使用for循環(huán)遍歷數(shù)組的元素
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]); // 通過索引訪問元素
}
}
}
public class ArrayDemo05 {
public static void main(String[] args) {
int[] arr = { 4, 1, 6, 3, 9, 8 }; // 定義一個數(shù)組
int max = arr[0]; // 定義變量max用于記住最大數(shù),首先假設(shè)第一個元素為最大值
// 下面通過一個for循環(huán)遍歷數(shù)組中的元素
for (int x = 1; x < arr.length; x++) {
if (arr[x] > max) { // 比較 arr[x]的值是否大于max
max = arr[x]; // 條件成立,將arr[x]的值賦給max
}
}
System.out.println("max=" + max); // 打印最大值
}
(1)越界異常:
訪問數(shù)組的元素時,索引不能超出0~length-1這個范圍。
(2)空指針異常:
在使用變量引用一個數(shù)組時,變量必須指向一個有效的數(shù)組對象,如果該變量的值為null,則意味著沒有指向任何數(shù)組,此時通過該變量訪問數(shù)組的元素會出現(xiàn)空指針異常。
(1)定義方式:
int[][] arr = new int[3][4];(前面是二維的長度,后面是一維的長度)
int[][] arr = new int[3][];(指定二維的長度)
int[][] arr = {{1,2},{3,4,5,6},{7,8,9}};
(2)二維數(shù)組的遍歷和求和:
int[][] arr2 = { {1,2},{3,4,5},{6,7,8,9,10} };
int sum2 = 0;
for (int i=0; i<arr2.length; i++) {
for (int j=0; j<arr2[i].length; j++) {
//System.out.println(arr2[i][j])
sum2 += arr2[i][j];
}
}
System.out.println("sum2= "+ sum2);
}
}
以上就是動力節(jié)點小編介紹的"Java中的數(shù)組介紹",希望對大家有幫助,如有疑問,請在線咨詢,有專業(yè)老師隨時為您服務(wù)。