我有以下问题:
给定矩阵的每一行的值,各列之间用空格隔开-因此我将所有行值输入到String数组中,删除空格并将数字解析为int数组。现在,每行的值看起来像1个数字“ 12345”,而应为“ 1 2 3 4 5”。

如何首先分隔数字,然后通过将元素添加到每一行来填充矩阵?谢谢!
这是我的代码:

    String n1 = input.nextLine ();
    int n = Integer.parseInt(n1); //rows of the matrix
    String[] arr = new String [n]; //contains all the rows of the matrix
    int [] array = new int [arr.length]; // contains all the elements of the rows of the matrix without whitespace

    for (int i = 0; i < arr.length; i++) {
        arr [i] = input.nextLine().replaceAll("\\s+","");
        array[i] = Integer.parseInt(arr[i]);
    }

    int matrix [][] = new int [n][arr[0].length()];

最佳答案

您应该split()用一些字符(示例中的空格)输入String。

示例如何将String转换为String的数组(使用split()方法)

// Example input
String input  = "1 2 3 4 5";

// Split elements by space
// So you receive array: {"1", "2", "3", "4", "5"}
String[] numbers = input.split(" ");

for (int position = 0; position < numbers.length; position++) {
    // Get element from "position"
    System.out.println(numbers[position]);
}


示例如何将String转换为int的数组

// Example input
String input = "1 2 3 4 5";

// Split elements by space
// So you receive array: {"1", "2", "3", "4", "5"}
String[] strings = input.split(" ");

// Create new array for "ints" (with same size!)
int[] number = new int[strings.length];

// Convert all of the "Strings" to "ints"
for (int position = 0; position < strings.length; position++) {
    number[position] = Integer.parseInt(strings[position]);
}

07-25 22:43
查看更多