More convenient way to find the max of 2+ numbers?
java, math
Solution
You could use 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));
}
Alternatively:
public static int max(int first, int... rest) {
int ret = first;
for (int val : rest) {
ret = Math.max(ret, val);
}
return ret;
}
Problem
I want code that accepts more than 2 integers and prints out the biggest one. I used `Math.MAX` but the problem is that it accepts only 2 integers by default, and you can't print all the ints in it. So I had to make it like this: ``` int max = Math.max(a, Math.max(b, Math.max(c, Math.max(d, e)))); ``` Is there a better method to do this?