Java评估许多变量中的最小数量

use*_*149 2 java

我有四个变量,在调用函数之前我不会知道,但是我需要确定四个变量中哪个变量最少.有没有很多if else语句的快速方法可以做到这一点,还是唯一的方法?如果相等则需要返回.

int TOP, BOTTOM, LEFT, RIGHT;

String MIN;

 min(TOP, BOTTOM, LEFT, RIGHT)
{
     FOUND MINNUM;
     return MINSTRING;
}
Run Code Online (Sandbox Code Playgroud)

我意识到,如果有多个相等的值,我需要一致地返回相同的相等值,并且如果我返回等于选择为min的方向的字符串,我可以一致地返回它.然后我可以检查字符串而不是整数更准确.

Dmi*_*urg 5

你可以使用嵌套的Math.mins:

int min(int top, int bottom, int left, int right) {
    return Math.min(Math.min(top, bottom), Math.min(left, right));
}
Run Code Online (Sandbox Code Playgroud)

另外,您可以介绍更常用的方法:

int min(Integer... nums) {
    if (nums.length == 0)
        throw new IllegalArgumentException("???");
    int res = nums[0];
    for (int i = 1; i < nums.length; ++i)
        res = Math.min(res, nums[i]);
    return res;
}
Run Code Online (Sandbox Code Playgroud)