Java,在数组中找到最小的数字 [英] Java, Finding smallest number in an array

查看:47
本文介绍了Java,在数组中找到最小的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是过去论文中的一个问题.我被要求创建一个静态方法 arrayMin 来查找数组 arr 中的最小值.

Ths is a question from a past paper. I have been asked to create a static method arrayMin to find the smallest value in the array arr.

我必须使用 while 循环,并且在每次迭代中,变量 min 将返回第一个 i 元素中的最小数字.

I have to use a while loop and on each iteration, the variable min will return the smallest number from the first i elements.

有没有办法在不调用另一个方法/for循环并严格使用while循环的情况下做到这一点,因为这个问题只值4%(包括编写循环不变量和javadoc).不确定我是否把问题复杂化了.

Is there a way to do this without calling another method/for loop and strictly using the while loop, as the question is only worth 4%(including writing loop invariants and javadoc). Not sure if I am overcomplicating the problem.

public class Revision {

public static int arr[] = new int[] { 5, 8, 4, 3, 6, 2 };
public static int min = 1;

public static int arrayMin() {

    int i = 0;

    if (arr == null) {
        return 0;

    } else {
        while (i < arr.length) {
            // some function/method call to find smallest number of arr[i]
            i++;
            return min;
        }
    }
    return min;
}

public static void main(String[] args) {

    System.out.println(arrayMin());
}

}

推荐答案

一些事情:

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

这篇关于Java,在数组中找到最小的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆