2011-05-03 63 views
1

我想要打印出二維數組中的最大數字。我的問題是我的輸出是三個數字而不是一個 - 最大的。爲什麼?在二維數組中打印最大數字 - 爲什麼我的代碼打印三個數字

這裏是我的代碼:

public class Main { 

/** 
* @param args the command line arguments 
*/ 
public static void main(String[] args) { 

    int maxRows = 3; 
    int maxCols = 4; 

    int [] onedArray = new int [maxRows]; 
     for (int i = 0; i < maxRows; i++){ 
     onedArray[i] = (int) ((Math.random() * 100) * maxCols); 
    } 

    int [][] twodArray = new int[maxRows][]; 
     for (int i = 0; i < maxRows; i++){ 
     twodArray[i] = new int[maxCols]; 
    } 

     for (int i = 0; i < twodArray.length; i++){ 
     for (int j = 0; j < twodArray[i].length; j++){ 
      twodArray[i][j] = (int) (Math.random() * 100); 
     } 
    } 

    System.out.println("2 - The 2D array: "); 
    for (int i = 0; i < twodArray.length; i++){ 
     for (int j = 0; j < twodArray[i].length; j++){ 
      System.out.print(twodArray[i][j] + " "); 
     } 
     System.out.println(""); 
    } 
    int maxValue = 1; 
    System.out.println("\nMax values in 2D array: "); 
    for (int i = 0; i < twodArray.length; i++) { 
     for (int j = 0; j < twodArray.length; j++) 
     if (twodArray[i][j] > maxValue) { 
     maxValue = twodArray[i][j]; 
     } 
      System.out.println(maxValue); 
     } 



} 

}

回答

5

的一切行動,直到最後一個序列的指示是正確的(雖然格式不正確)。

以下是原文:

int maxValue = 1; 
System.out.println("\nMax values in 2D array: "); 
for (int i = 0; i < twodArray.length; i++) { 
    for (int j = 0; j < twodArray.length; j++) 
    if (twodArray[i][j] > maxValue) { 
    maxValue = twodArray[i][j]; 
    } 
     System.out.println(maxValue); 
    } 

這裏是更好的版本:

int maxValue = 0; 
System.out.println("\nMax values in 2D array: "); 
for (int i = 0; i < twodArray.length; i++) { 
    for (int j = 0; j < twodArray[i].length; j++) { 
     if (twodArray[i][j] > maxValue) { 
      maxValue = twodArray[i][j]; 
     } 
    } 
    System.out.println("Max value of row " + i + ": " + maxValue); 
} 

細心觀察,你會看到,我添加了{字符第二for循環之後。

如果你想找到總最大的,這裏儘量減少開啓和關閉大括號是另外一個版本:

int maxValue = 0; 

System.out.println("\nMax values in 2D array: "); 
for (int i = 0; i < twodArray.length; i++) 
    for (int j = 0; j < twodArray[i].length; j++) 
     if (twodArray[i][j] > maxValue) 
      maxValue = twodArray[i][j]; 

System.out.println("Maximum value: " + maxValue); 

好運。

1

你行System.out.println(maxValue);需要在變量i走出來的循環。它被打印3次,因爲它在這個循環中。

如果您的代碼縮進正確,這將更容易看到;無論如何,這是一個好習慣。

1

答案就在你的代碼,一旦它的正確縮進:

for (int i = 0; i < twodArray.length; i++) { 
    for (int j = 0; j < twodArray.length; j++) 
     if (twodArray[i][j] > maxValue) { 
      maxValue = twodArray[i][j]; 
     } 
     System.out.println(maxValue); 
    } 
} 

不要小看好多麼有用縮進可用於捕獲這種錯誤:)

+1

你還應該修復'j Ishtar 2011-05-03 21:22:55