2017-11-17 115 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++; 
}