【问题标题】:Java - How to populate 2d array with nested while loops?Java - 如何使用嵌套的 while 循环填充二维数组?
【发布时间】:2017-11-17 23:47:07
【问题描述】:

我只需要使用嵌套的 while 循环来填充用户输入的双精度数组。这是我目前所拥有的:

public static double[][] score() {
        int col = 3;
        int row = 3;
        int size = 0;
        Scanner in = new Scanner(System.in);
        double[][] scores = new double[row][col];
        System.out.println("Enter your scores: ");
        while (in.hasNextDouble() && size < scores.length) {
            while (size < scores[size].length) {
                scores[][] = in.hasNextDouble();
                size++;
            }
            return scores;
        }

【问题讨论】:

  • 你事先知道数组的大小吗?
  • 3 行 3 列,所以我总共需要 9 个输入。

标签: java arrays loops while-loop


【解决方案1】:

最常用的方法是通过for 循环,因为它们允许您以简洁的方式指定所需的索引计数器:

for(int i = 0; i < scores.length; i++){
    for(int j = 0; j < scores[i].length; j++){
        scores[i][j] = in.nextDouble();
    }
}

如果你特别需要使用 while 循环,你可以做几乎相同的事情,它只是分成多行:

int i = 0;
while(i < scores.length){
    int j = 0;
    while(j < scores[i].length){
        scores[i][j] = in.nextDouble();
        j++;
    }
    i++;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多