Reputation: 417
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...
Upvotes: 2
Views: 10845
Reputation: 51
Code to find the greatest of three numbers using ternary operator:
public class FindGraterUsingTernaryOperator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the 3 Numbers to Check the Grater:::");
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int result = c > (a > b ? a : b) ? c : ((a > b) ? a : b);
System.out.println("Grater Between 3 Numbers Is::" + result);
}
}
Upvotes: 0
Reputation: 45
To get the max value out of three numbers, one line method:
int min = (a < b && a < c) ? a : ((b < a && b < c) ? b : c);
Upvotes: 0
Reputation: 425208
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));
}
Upvotes: 1
Reputation: 3652
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)
Upvotes: 3