【问题标题】:Java: Constructing a 2D Matrix Array According to User Input Using a ScannerJava:使用扫描仪根据用户输入构造二维矩阵数组
【发布时间】:2020-11-25 01:44:11
【问题描述】:

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

【问题讨论】:

  • 一行的输入应该是11 2 4,还是应该是单独的输入1124
  • 嗨,数组中的每个元素都是一行中的单独输入。

标签: java arrays list matrix integer


【解决方案1】:

执行以下操作:

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

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

【讨论】:

    【解决方案2】:

    您可以将输入逐行读取为字符串,检查其有效性,对其进行解析并将其填充到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-loop 仅用于打印结果,只是为了检查它是否有效:

    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 或任何矩阵!
    我希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-13
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多