2011-05-03 56 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