Comparing three numbers with the Java logical-ternary operator?

10,087

Solution 1

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

return (n1 <= n2) && (n1 <= n3) ? n1 : (n2 <= n3)? n2 : n3

(note: not actually tested)

Solution 2

This works for me (I made them int for easier testing):

public static int findSmallestOfThree(int n1, int n2, int n3) {
    return n1 < n2 ? n1 < n3 ? n1 : n3 : n2 < n3 ? n2 : n3;
}

If you care more about readability than speed:

public static int findSmallestOfThree(int n1, int n2, int n3) {
    return Math.min(n1, Math.min(n2, n3));
}

Here's some simple test code:

public static void main(String[] args) {
    System.out.println(findSmallestOfThree(9, 10, 11));
    System.out.println(findSmallestOfThree(10, 9, 11));
    System.out.println(findSmallestOfThree(10, 11, 9));
    System.out.println(findSmallestOfThree(11, 10, 9));
    System.out.println(findSmallestOfThree(9, 11, 10));
    System.out.println(findSmallestOfThree(11, 9, 10));
}
Share:
10,087
Bob
Author by

Bob

Updated on June 05, 2022

Comments

  • Bob
    Bob almost 2 years

    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...