我試圖弄清楚如何從標準輸入中讀取多維陣列,因為用戶提供了行和列大小,后跟陣列的整數
例如輸入:
2 3 <= row, col of array
8 3 10 < array integers
7 9 6
我的代碼目前是:
int colA = scan.nextInt();
int rowA = scan.nextInt();
int[][] array = new int[rowA][colA];
for (int i = 0; i <rowA;i ){
for (int j=0; j<colA;j ){
array1[i][j] = scan.nextInt();
}
}
我的陣列的輸出是: [[8,3,10,7,9,6]] 但我想做的是輸出[[8,3,10],[7,9,6]]
uj5u.com熱心網友回復:
這里首先從用戶那里得到的行和列值是相反的,這是我能看到的唯一錯誤 import java.util.Arrays; 匯入 java.util.Scanner;
公共類二維陣列{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int rowA = scan.nextInt();
int colA = scan.nextInt();
int[][] array = new int[rowA][colA];
for (int i = 0; i < rowA; i ) {
for (int j = 0; j < colA; j ) {
array[i][j] = scan.nextInt();
}
}
for (int[] innerArray : array) {
System.out.println(Arrays.toString(innerArray));
}
}
這是一個作業
uj5u.com熱心網友回復:
您的代碼中有一些錯誤。
您顛倒了向用戶詢問的維度的順序。
用這個:
int rowA = scan.nextInt(); int colA = scan.nextInt();而不是這個:
int colA = scan.nextInt(); int rowA = scan.nextInt();你寫而
array1不是arrayarray1[i][j] = scan.nextInt();
請注意,您可以使用array[i][j] = scan.nextInt();而不是array[i][j] = scan.nextInt()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/436806.html
上一篇:如何將陣列“翻譯”為標簽?
