更方便的方法来找到最多2+个数字?

Sar*_*mer 6 java math

我希望代码接受超过2个整数并打印出最大的整数.我用过,Math.MAX但问题是它默认只接受2个整数,你不能在其中打印所有的整数.所以我不得不这样做:

int max = Math.max(a, Math.max(b, Math.max(c, Math.max(d, e))));
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来做到这一点?

NPE*_*NPE 8

你可以使用varargs:

public static Integer max(Integer... vals) {
    Integer ret = null;
    for (Integer val : vals) {
        if (ret == null || (val != null && val > ret)) {
            ret = val;
        }
    }
    return ret;
}

public static void main(String args[]) {
    System.out.println(max(1, 2, 3, 4, 0, -1));
}
Run Code Online (Sandbox Code Playgroud)

或者:

public static int max(int first, int... rest) {
    int ret = first;
    for (int val : rest) {
        ret = Math.max(ret, val);
    }
    return ret;
}
Run Code Online (Sandbox Code Playgroud)

  • 也许看看它超过5秒,并尝试理解. (9认同)