Java基础学习:3、数组
1、三种声明方式:
// 创建一个double数据类型的数组,长度为5
double array[] = new double[5];
// 创建int数据类型数组,长度为6
int age[] = {12,11,22,32,90,17};
数组扩容:
public static void main(String[] args) {
int[] oldArray = {1, 2, 3, 4};
Scanner myScanner = new Scanner(System.in);
do {
int[] newArray = new int[oldArray.length + 1];
for (int i = 0; i < oldArray.length; i++) {
newArray[i] = oldArray[i];
}
System.out.println("请输入要要添加元素");
int addNum = myScanner.nextInt();
newArray[newArray.length - 1] = addNum;
oldArray = newArray;
System.out.println("====newOld扩容后情况====");
for (int i = 0; i < newArray.length; i++) {
System.out.println(newArray[i]);
}
System.out.println("=====是否继续添加 y/n =======");
char key = myScanner.next().charAt(0);
if(key == 'n') {
break;
}
} while(true);
}
2、二维数组:
动态初始化:
// [2]:表示二维数组里面有两个一维数组,[3]:每一个一维数组里面有三个元素 int arr[][] = new int[2][3];
arr[1][1] = 8; // 将第一个一维数组里面的第二个元素赋值为8 for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { System.out.print(arr[i][j]); } System.out.println(); } }
/** 打印结果
000
080*/
静态初始化:
public static void main(String[] args) {
int[][] arr = {{1,2, 3, 4, 5},{6,7,8,9,10},{11,12,13,14,15},{16,17,18,19,20}};
// 二维数组里面每一个一维数组个数可以不一致
int[][]arr2 = {{1,2,3},{4,5},{7,2,23,12}};
for (int i = 0; i < arr.length; i++) {
for(int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j]);
}
System.out.println();
}
}
------------恢复内容结束------------