我有一个这样的字符串数组
3
1 5 5
2 -2 -3
15 -100 20
我如何将其转换为二维数组
1 5 5
2 -2 -3
15 -100 20
3是2d的大小
public static class convert(String[] lines){
int n = Integer.parseInt(lines[0]);
int[][] matrix = new int[n][n];
for (int j = 1; j < n; j++) {
String[] currentLine = lines[j].split(" ");
for (int i = 0; i < currentLine.length; i++) {
matrix[j][i] = Integer.parseInt(currentLine[i]);
}
}
}
没有,
你有几个Off-by-one errors
。
试试这个:
int n = Integer.parseInt(lines[0]);
int[][] matrix = new int[n][n];
for (int j = 1; j <= n; j++) {
String[] currentLine = lines[j].split(" ");
for (int i = 0; i < currentLine.length; i++) {
matrix[j-1][i] = Integer.parseInt(currentLine[i]);
}
}
请让我知道,如果你有任何问题!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句