java - 使用来自字符串的输入填充二维数组的行

标签 java arrays matrix multidimensional-array

我有以下问题: 我的矩阵的每一行的值都是给定的,列由空格分隔 - 所以我在一个字符串数组中输入所有行值,删除空格并将数字解析为一个 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 数组(使用 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]);
}

关于java - 使用来自字符串的输入填充二维数组的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55066366/

相关文章:

Java 包装器 : overriding a method called in the super constructor

c++ - 多维数组传输问题

r - 将字符串矩阵拆分为R中的数字矩阵

java - 禁用警告变量可能尚未初始化?

java - 如何验证是否使用任何参数调用了方法?

python - 根据没有for循环的一维数组中的值更改二维numpy数组中的某些值

python - 数组中的 Numpy 条件乘法数据(如果为真乘以 A,则为假乘以 B)

c++ - DLIB C++ 如何制作 dlib::matrix 的 std::vector

matlab - 如何计算矩阵中每列值的数量

java - 这是 HashMap 的有效单元测试吗?