繁体   English   中英

Java:使用扫描仪根据用户输入构造二维矩阵数组

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM