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

标签 java multidimensional-array numbers max

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

这是我的代码:

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);
        }



}

最佳答案

直到最后一个指令序列之前的所有内容都是正确的(尽管格式不正确)。

原文如下:

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);

祝你好运。

关于java - 打印二维数组中的最大数字 - 为什么我的代码打印三个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5875813/

相关文章:

java - com.sun.jdi.InvocationException 发生调用方法

arrays - 快速创建嵌套数组

java - 如何从特定点开始迭代二维数组?

c - 在c中添加巨大的数字会产生错误的结果

python - 检查字符串是否为实数

java - 我的应用程序崩溃了,因为根据垃圾收集器的说法,仅剩余 4% 的堆内存...我该如何防止这种情况发生?

java - 什么时候应该关闭 HttpClient?

java - Java 8 121 中需要 BouncyCasSTLe 吗?

php - 我想根据日期对多维数组进行排序,并计算数组中数据出现的数量

Oracle float 与数字