首页 > 解决方案 > Java:使用扫描仪根据用户输入构造二维矩阵数组

问题描述

我正在尝试使用扫描仪读取二维 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 矩阵数组的末尾?谢谢你。

标签: javaarrayslistmatrixinteger

解决方案


请执行下列操作:

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

只要您进行上述更改,您的程序就可以正常工作。但是,我建议您拆分"\\s+"以允许数字之间有任意数量的空格。


推荐阅读