【问题标题】:Am having trouble finding the minimum value in a 2D array [duplicate]在二维数组中找到最小值时遇到问题[重复]
【发布时间】:2020-10-16 13:05:16
【问题描述】:

这是我的示例代码,我无法找到最小的变量。它总是返回零,同时找到最大的变量工作正常。 我使用了相同的技术,但不知道哪里出错了。

请帮帮我。

    for (int i = 0; i < n; i++) {
        smallest = array[i][0];
        largest = array[i][0];//set largest to 0 at each round
        mean = 0;
        
        System.out.print("Round " + (i + 1) + " Cards: ");
        Scanner in = new Scanner(System.in);

        while (in.hasNext()) {
            if (in.hasNextInt()) {
                for (int j = 0; j < m; j++) {
                    array[i][j] = in.nextInt();
                    if (array[i][j] > 9) {
                        System.out.println("Must be between 1-9");
                        // Arrays.fill(array, null);
                        j = 0;
                        System.out.print("Round " + (i + 1) + " Cards: ");
                    }
                    // Largest value
                    if (array[i][j] >= largest) {
                        largest = array[i][j];  
                    }
                    
                    // Smallest value
                    //smallest = array[i][0];
                    if (array[i][j] < smallest) {
                        smallest = array[i][j];
                         
                    }
  
                    // total
                    mean += array[i][j];
                }
                break;
            } else {
                in.next();
            }

        }
        //mean calculation
        array[i][m] = largest;
        array[i][m + 1] = smallest;
        array[i][m + 2] = (int) mean / m;

    }

【问题讨论】:

  • 是我的方法那么复杂。请帮助我是新手。
  • 第二个for循环中使用的变量m在哪里?
  • M 用于打印值
  • m 表示列数和 n 行数
  • mn 有什么价值?

标签: java


【解决方案1】:

这将是一种在二维数组中查找最小值和最大值的简洁方法。 如果我正确理解您在 cmets 中要说的内容,您可以将 i &lt; array.length 替换为 m 并将 i &lt; array[i].length 替换为 n

public static void main(String[] args) {
        int[][] array = new int[][]{{7, 8, 32439, 0}, {1, -32, 3, 5}};
        int smallest = Integer.MAX_VALUE;
        int largest = Integer.MIN_VALUE;

        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                if (array[i][j] < smallest) {
                    smallest = array[i][j];
                }
                if (array[i][j] > largest) {
                    largest = array[i][j];
                }
            }
        }

        System.out.println(smallest);
        System.out.println(largest);
    }

输出:

-32

32439

【讨论】:

  • 问题出在代码的 if(array[i][j]
  • 我的 if 块没有返回任何东西,它分配了变量 smallestan int。并提示:您应该阅读您的输入,然后检查最小/最大值。使您的代码更具可读性,并且通常任务一个接一个地执行。
  • 我发现了问题。我只是将平均计算移至内部 for 循环,一切正常。索引值被引用的问题。
猜你喜欢
  • 1970-01-01
  • 2019-12-20
  • 2015-04-25
  • 1970-01-01
  • 2013-10-26
  • 2012-04-21
  • 1970-01-01
  • 2017-03-09
  • 1970-01-01
相关资源
最近更新 更多