I’m trying to create a method that returns the smallest value of three values (all bytes). Here is what I have:
public static byte findSmallestOfThree(byte n1, byte n2, byte n3) {
return n1 > n2 ? n2 : n1 > n3 ? n3 : n1;
}
Now, the issue I’m having is that it doesn’t always work.
Here are some inputs, and the outputs:
9, 10, 11 -> 9
10, 9, 11 -> 9
10, 11, 9 -> 9
11, 10, 9 -> 10
As you can see, when I entered 11, 10, 9 (in that order), I got 10 as the result (even though it should have been 9).
What is wrong with my logic? I think I’ve messed something up with the ternary operators, but I’m not sure what it is…
It’s not a mistake with the ternary operators; it’s a mistake with the comparisons. Your code says: if n1 > n2, return n2. So in the fourth example, 11 > 10, so it returns 10.
You have to compare n1 to both n2 and n3 to know that it’s the greatest or lowest. You really want something like
(note: not actually tested)