【发布时间】:2020-10-21 09:25:58
【问题描述】:
我真的不知道如何将列表中的单个元素分配给二维数组。例如:
我有一个字符串列表,它包含:
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;
【问题讨论】:
-
在找到 space(" ") 的地方拆分列表中的每个元素,并将拆分的部分存储在另一个一维数组中。例如 num = [1,2,3,1,4,2]。然后使用嵌套循环访问 2D 数组的索引,并将 1D 数组中的元素插入其中。