2 回答
TA贡献1777条经验 获得超3个赞
如果你想在java中创建一个多维数组,你应该使用这个语法:
int n = ...;
int array[][] = new int[n][n];
例如:
try (Scanner sc = new Scanner(System.in)) {
int n = sc.nextInt();
int arr[][] = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = sc.nextInt();
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.println(arr[i][j]);
}
System.out.println();
}
}
一些最后的笔记:
完成后应该关闭流
您不会“告诉编译器”,因为编译器不会在运行时执行。无论如何,您的意思是JVM。
TA贡献1784条经验 获得超7个赞
这是一个关于如何构建具有不同大小行的二维数组的解决方案。每个数组都是在我们询问其大小后创建的
Scanner sc = new Scanner(System.in);
System.out.println("Number of arrays");
String str1 = sc.nextLine();
int numberOfArrays = Integer.valueOf(str1);
int[][] array = new int[numberOfArrays][];
for (int i = 0; i < numberOfArrays; i++) {
System.out.println("Size of array");
String str2 = sc.nextLine();
int size = Integer.valueOf(str2);
int[] row = new int[size];
for (int j = 0; j < size; j++) {
System.out.println("Value:");
String str3 = sc.nextLine();
int value = Integer.valueOf(str3);
row[j] = value;
}
array[i] = row;
}
}
更新
这是一个允许在一行中输入数组中的所有数字的版本。请注意,这里没有错误处理检查给定值与预期值的数量等。
for (int i = 0; i < numberOfArrays; i++) {
System.out.println("Size of array");
String str2 = sc.nextLine();
int size = Integer.valueOf(str2);
int[] row = new int[size];
System.out.println("Values:");
String str3 = sc.nextLine();
String[] numbers = str3.split("\\s");
for (int j = 0; j < size; j++) {
row[j] = Integer.valueOf(numbers[j]);
}
array[i] = row;
}
添加回答
举报
