打印二维数组中的最大数字 - 为什么我的代码打印三个数字

2022-01-17 00:00:00 multidimensional-array max numbers java

我正在尝试打印二维数组中的最大数字.我的问题是我的输出是三个数字而不是一个 - 最大的.为什么?

I am trying to print out the largest number in a 2D array. My problem is that my output are three numbers instead of one - the largest. Why?

这是我的代码:

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("
Max 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);
        }



}

}

推荐答案

直到最后一个指令序列为止的一切都是正确的(尽管格式很差).

Everything up until the last sequence of instructions is correct (although poorly formatted).

这是原文:

int maxValue = 1;
System.out.println("
Max 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("
Max 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 循环之后添加了 { 字符.

Look carefully and you'll see that I added the { character after the second for-loop.

如果您想找到总最大值,并最小化打开和关闭花括号,这里是另一个版本:

If you wanted to find total max, and minimize open and close curly-braces here is another version:

int maxValue = 0;

System.out.println("
Max 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);

祝你好运.

相关文章