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