[英]Java: Constructing a 2D Matrix Array According to User Input Using a Scanner
我正在嘗試使用掃描儀讀取二維 3x3 矩陣的元素。 輸入看起來像這樣:
3
11 2 4
4 5 6
10 8 -12
我目前收到錯誤:
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
scan.next();
List<List<Integer>> array = new ArrayList<>();
for (int i = 0; i < a; i++) {
String number = scan.nextLine();
String[] arrRowItems1 = number.split(" ");
List<Integer> list = new ArrayList<>();
for (int j = 0; j < a; j++) {
int arrItem = Integer.parseInt(arrRowItems1[j]);
list.add(arrItem);
}
array.add(list);
}
scan.close();
我如何 go 關於做這個問題,以便根據用戶輸入構造一個 2d 3x3 矩陣數組? 謝謝你。
請執行下列操作:
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
scan.nextLine(); // change to nextLine
只要您進行上述更改,您的程序就可以正常工作。 但是,我建議您拆分"\\s+"
以允許數字之間有任意數量的空格。
您可以將輸入逐行讀取為字符串,檢查其有效性,對其進行解析並將其填充到int[][]
-Matrix 中。
這樣,程序會一直要求輸入,直到它得到三行有效的數字:
Scanner scan = new Scanner(System.in);
int dim = 3; //dimensions of the matrix
int line = 1; //we start with line 1
int[][] matrix = new int[dim][dim]; //the target matrix
while(line <= dim) {
System.out.print("Enter values for line " + line + ": "); //ask for line
String in = scan.nextLine(); //prompt for line
String[] nums; //declare line numbers array variable
//check input for validity
if (!in.matches("[\\-\\d\\s]+")
| (nums = in.trim().split("\\s")).length != dim) {
System.out.println("Invalid input!");
continue;
}
//fill line data into target matrix
for (int i = 0; i < nums.length; i++) {
matrix[line - 1][i] = Integer.parseInt(nums[i]);
}
line++; //next line
}
scan.close(); //close scanner (!)
//test output
for (int i = 0; i < matrix.length; i++) {
System.out.println(Arrays.toString(matrix[i]));
}
最后一個for
循環僅用於打印結果,只是為了檢查它是否有效:
Enter values for line 1: 11 2 4
Enter values for line 2: 4 5 6
Enter values for line 3: 10 8 -12
[11, 2, 4]
[4, 5, 6]
[10, 8, -12]
順便說一句,通過更改dim
(尺寸)的值,您甚至可以獲得 5x5 或任何矩陣!
我希望這有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.