简体   繁体   中英

Java - How to populate 2d array with nested while loops?

I need to populate a double array with user input by using nested while loops only. This is what I have so far:

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;
        }

The most common way to do this is through for loops since they allow you to specify the index counters you need in a concise way:

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

If you specifically need to use while loops you can do pretty much the same thing, its just broken up into multiple lines:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM