2017-11-17 116 views
0

我需要通过使用嵌套的while循环只填充用户输入的双数组。这是我到目前为止有:Java - 如何使用嵌套while循环填充2d数组?

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

你知道前手的数组的大小? – luckydog32

+0

3行,3列,所以我需要9总输入。 – MetalGearRyan

回答

4

最常见的方式做,这是通过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++; 
}