java - 卡在二维数组中

标签 java for-loop multidimensional-array

我正在尝试编写一个程序来读取包含如下 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/

相关文章:

java - @Resource UserTransaction 为空

java - 使用 String hashCode() 方法?

java - Java设计类时在ArrayList中添加对象

json - 如何在 Pure Batch 中解析 JSon

ios - For循环不改变变量

c - 有限状态机中的数组、指针和指向函数的指针

java - 在类构造函数中实例化 ArrayList

for循环中的Python变量范围

PHP - 遍历多个表并填充多维数组

php - 实现类似 goMongoDB 的查询表达式对象评估