There was a question posted on one of the forums, which I picked up to play with. It was very straight-forward, so seemed like a nice place to start!

Question: I’ve written a function to determine the biggest integer from two supplied integers. How would I increase that to 3 integers.

Answer:

If you could guarantee that requirements would never change past comparing three numbers it’d be a very simple case of passing the returned highest number and 3rd number to the same function.

However, possibly the safest option moving forward would be make use of the variable arguments functionality in Java, so the function could accept as many numbers as you could ever want to throw at it. So the function would look like this:

static public int maxVar(int... nums) {
if (nums.length == 0) throw new IllegalArgumentException("No values supplied");
int result = Integer.MIN_VALUE;
for (int i: nums) {
if (i > result)
result = i;
}
return result;
}

### Like this:

Like Loading...

*Related*