我正在尝试编写一个程序来读取包含如下 double 列表的文本文件(很好):
1.0, 2.0, 3.0
4.0, 5.0, 6.0
7.0, 8.0, 9.0
_
public static void main(String[] args) {
Scanner inputStream = null;
try {
inputStream = new Scanner(new FileInputStream("tstc.txt"));
}
catch (FileNotFoundException e) {
System.out.println(e.getMessage());
System.out.println("Program aborted.");
System.exit(0);
}
double[][] arrayNums = new double[3][3];
for(int sec = 0; sec < 3; sec++) {
while(inputStream.hasNextLine()) {
String line = inputStream.nextLine();
String[] lineList = line.split(", ");
int pos = 0;
for(int motor = 0; motor < 3; motor++) {
double lineDouble = Double.parseDouble(lineList[pos]);
arrayNums[motor][sec] = lineDouble;
pos+=1;
}
}
}
System.out.println(Arrays.deepToString(arrayNums));
这就是我想要的:
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]
但这就是我得到的:
[[7.0, 0.0, 0.0], [8.0, 0.0, 0.0], [9.0, 0.0, 0.0]]
我已经发现我的问题在于 sec 变量保持不变,但我不确定如何在不更改整个代码结构的情况下重新排列代码。
任何提示将不胜感激。
最佳答案
这应该像预期的那样工作。
int pos = 0;
while(inputStream.hasNextLine()) {
String line = inputStream.nextLine();
String[] lineList = line.split(", ");
for(int motor = 0; motor < 3; motor++) {
double lineDouble = Double.parseDouble(lineList[motor]);
arrayNums[pos][motor] = lineDouble;
}
pos++;
}
System.out.println(Arrays.deepToString(arrayNums));
不要忘记删除第一个循环。
关于java - 卡在二维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33401804/