且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java,在数组中找到最小的数字

更新时间:2022-11-14 08:34:36

一些事情:

  1. 数组不应该是静态的,你应该将它作为参数传递给arrayMin方法;
  2. min 应该是一个局部的 arrayMin 变量,而不是静态的;
  3. min 应初始化为 Integer.MAX_VALUE.如果你用 1 初始化它,而 2 恰好是数组的最小值,你永远不会返回它;
  4. 您不能从一个方法中多次返回.一旦你执行return min,方法就结束了.可能对 变量 min 将返回第 i 个元素中的最小数字 短语有些混淆.这可能意味着在每次迭代中,变量min(不返回)第一个i的最小数字代码>元素.
  1. The array shouldn't be static, you should pass it as a parameter to the arrayMin method;
  2. min should be a local arrayMin variable, not static;
  3. min should be initialized to Integer.MAX_VALUE. If you initialize it with 1, and 2 happens to be the min value of the array, you'll never return it;
  4. You can't return multiple times from a method. As soon as you do return min, the method ends. There's probably some confusion over the the variable min will return the smallest number from the first i elements phrase. It probably means that in each iteration, the variable min will have (not return) the smallest number from the first i elements.

这是一个重构:

public static int arrayMin(int[] arr) {
    int i = 0;
    int min = Integer.MAX_VALUE;
    if (arr == null) {
        return 0; // What if 0 is the minimum value? What do you want to do in this case?
    } else {
        while (i < arr.length) {
            if (arr[i] < min) {
              min = arr[i];
            }
            i++;
        }
    }
    return min;
}