我真的不知道如何定义列表中各个元素到2D数组的分配。例如:
我有一个字符串列表,它包含:
list.get(0) = "1 2 3"
list.get(1) = "1 4 2"
我希望每个元素都这样分配int[][]
:
tab[0][0] = 1;
tab[0][1] = 2;
tab[0][2] = 3;
tab[1][0] = 1;
tab[1][1] = 4;
tab[1][2] = 2;
我准备了这样的代码:
Scanner scan = new Scanner(System.in);
List<String> stringToMatrix = new ArrayList<>();
while (!stringToMatrix.contains("end")) {
stringToMatrix.add(scan.nextLine());
}
stringToMatrix.remove(stringToMatrix.size() - 1);
//-size of matrix
int col = stringToMatrix.get(0).length() - stringToMatrix.get(0).split(" ").length + 1;
int rows = stringToMatrix.size();
int[][] bigMatrix = new int[rows+2][col+2]; //rows and cols +2 because I want to insert values from the list into the middle of the table.
int outerIndex = 1;
for (String line: stringToMatrix) {
String[] stringArray = line.split(" ");
int innerIndex = 1;
for (String str: stringArray) {
int number = Integer.parseInt(str);
bigMatrix[outerIndex][innerIndex++] = number;
}
outerIndex++;
}
for (int[] x: bigMatrix) {
System.out.print(Arrays.toString(x));
}
输入:
1 2 3
1 2 3
end
结果:
[0, 0, 0, 0, 0][0, 1, 2, 3, 0][0, 1, 2, 3, 0][0, 0, 0, 0, 0]
输入:
1 -2 53 -1
1 4 -4 24
end
结果
[0, 0, 0, 0, 0, 0, 0, 0, 0][0, 1, -2, 53, -1, 0, 0, 0, 0][0, 1, 4, -4, 24, 0, 0, 0, 0][0, 0, 0, 0, 0, 0, 0, 0, 0]
问题在那里:
int col = stringToMatrix.get(0).length() - stringToMatrix.get(0).split(" ").length + 1;
一个带有另一个嵌套循环的for循环将执行以下操作:
List<String> list = ... // input list
int[][] tab = new int[2][3]; // target array
int outerIndex = 0; // X-index of tab[X][Y]
for (String line: list) { // for each line...
String[] stringArray = line.split(" "); // ... split by a space
int innerIndex = 0; // ... Y-index of tab[X][Y]
for (String str: stringArray) { // ... for each item in a line
int number = Integer.parseInt(str); // ...... parse to an int
tab[outerIndex][innerIndex++] = number; // ...... add to array tab[X][Y]
} and increase the Y
outerIndex++; // ... increase the X
}
请记住,此外,您可能需要:
\\s+
)分隔,而不是一个空格如果您不介意Integer[][]
结果,那么Java 8 Stream API将为您提供更简便的方法。
Integer[][] tab2 = list.stream() // Stream<String>
.map(line -> Arrays.stream(line.split(" ")) // ... Stream<String> (split)
.map(Integer::parseInt)) // ... Stream<Integer>
.toArray(Integer[]::new)) // ... Integer[]
.toArray(Integer[][]::new); // Integer[][]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句