我希望代码接受超过2个整数并打印出最大的整数。我使用Math.MAX
,但问题是它默认只接受2个整数,并且你不能在其中打印所有的整数。所以我不得不这样做:
int max = Math.max(a, Math.max(b, Math.max(c, Math.max(d, e))));
有更好的方法吗?
答案 0 :(得分: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));
}
可替换地:
public static int max(int first, int... rest) {
int ret = first;
for (int val : rest) {
ret = Math.max(ret, val);
}
return ret;
}
答案 1 :(得分:1)
您可以使用简单的循环:
public Integer max(final Collection<Integer> ints) {
Integer max = Integer.MIN_VALUE;
for (Integer integer : ints) {
max = Math.max(max, integer);
}
return max;
}