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;
}
添加回答
舉報