Java:使用Scanner根据用户输入构建二维矩阵数组。

huangapple go评论62阅读模式
英文:

Java: Constructing a 2D Matrix Array According to User Input Using a Scanner

问题

我正在尝试使用扫描器读取一个2x2 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();

我该如何解决这个问题,以便根据用户输入构建一个2D 3x3矩阵数组?谢谢。

英文:

I am trying to read elements of a 2-d 3x3 matrix using a scanner.
The input would look something like this:

3
11 2 4
4 5 6
10 8 -12

I am current geting the error:

Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
scan.next();

List&lt;List&lt;Integer&gt;&gt; array = new ArrayList&lt;&gt;();

for (int i = 0; i &lt; a; i++) {
 
    String number = scan.nextLine();
    String[] arrRowItems1 = number.split(&quot; &quot;);
    List&lt;Integer&gt; list = new ArrayList&lt;&gt;(); 

    for (int j = 0; j &lt; a; j++) {
        int arrItem = Integer.parseInt(arrRowItems1[j]); 
        list.add(arrItem);
    }

    array.add(list);
}

scan.close();

How do I go about doing this problem, so that a the end a 2d 3x3 matrix array is constructed according to user input? Thank You.

答案1

得分: 2

以下是翻译好的部分:

做以下操作
```java
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
scan.nextLine(); // 更改为 nextLine

只要进行上述更改,您的程序将正常运行。但是,我建议您使用 &quot;\\s+&quot; 进行拆分,以允许数字之间的任意数量的空格。


<details>
<summary>英文:</summary>

Do the following:

Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
scan.nextLine(); // change to nextLine

Your program works just fine the way it was written as long as you make the above change.  However, I recommend you split on `&quot;\\s+&quot;` to allow any number of spaces between the numbers.

</details>



# 答案2
**得分**: 0

你可以将输入逐行读取为字符串,检查其有效性,解析它并填充到一个`int[][]`矩阵中。这样,程序会一直要求输入,直到获得三行有效的数字:

```java
Scanner scan = new Scanner(System.in);
int dim = 3; //矩阵的维度
int line = 1; //我们从第一行开始
int[][] matrix = new int[dim][dim]; //目标矩阵

while (line <= dim) {
    System.out.print("输入第" + line + "行的值:"); //询问行
    String in = scan.nextLine(); //提示输入行
    String[] nums; //声明行数字数组变量

    //检查输入的有效性
    if (!in.matches("[-\\d\\s]+")
            | (nums = in.trim().split("\\s")).length != dim) {
        System.out.println("无效输入!");
        continue;
    }

    //将行数据填充到目标矩阵中
    for (int i = 0; i < nums.length; i++) {
        matrix
[i] = Integer.parseInt(nums[i]); } line++; //下一行 } scan.close(); //关闭扫描器 //测试输出 for (int i = 0; i < matrix.length; i++) { System.out.println(Arrays.toString(matrix[i])); }

最后的for循环仅用于打印结果,用于检查是否正常工作:

输入第1行的值11 2 4
输入第2行的值4 5 6
输入第3行的值10 8 -12
[11, 2, 4]
[4, 5, 6]
[10, 8, -12]

顺便说一下,通过更改dim(维度)的值,您甚至可以获得5x5或其他尺寸的矩阵!希望这有所帮助!

英文:

You could read the input line-by-line as a string, check it for validity, parse it and fill it in an int[][]-Matrix.
This way, the program keeps asking for input until it got three valid lines of numbers:

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 &lt;= dim) {
	System.out.print(&quot;Enter values for line &quot; + line + &quot;: &quot;); //ask for line
	String in = scan.nextLine(); //prompt for line
	String[] nums; //declare line numbers array variable
	
	//check input for validity
	if (!in.matches(&quot;[\\-\\d\\s]+&quot;)
			| (nums = in.trim().split(&quot;\\s&quot;)).length != dim) {
		System.out.println(&quot;Invalid input!&quot;);
		continue;
	}
	
	//fill line data into target matrix
	for (int i = 0; i &lt; 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 &lt; matrix.length; i++) {
	System.out.println(Arrays.toString(matrix[i]));
}

The last for-loop is only for printing the result, just to check if it works:

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]

BTW by changing the value for dim (dimension) you could even get a 5x5 or whatever matrix!
I hope this helped!

huangapple
  • 本文由 发表于 2020年8月5日 06:06:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/63255734.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定