First off, the question is "Write a Java program to find the smallest of three numbers using ternary operators."
Here's my code:
class questionNine
{
public static void main(String args[])
{
int x = 1, y = 2, z = 3;
int smallestNum;
smallestNum = (x<y && x<z) ? x : (y<x && y<z) ? y : (z<y && z<x) ? z;
System.out.println(smallestNum + " is the smallest of the three numbers.");
}
}
I tried to use multiple conditions in the ternary operator but that doesn't work. I was absent a few days so I'm not really sure what to do and my teacher's phone is off. Any help?
We can nest ternary operators to test multiple conditions.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
Try
int min = x < y ? (x < z ? x : z) : (y < z ? y : z);
You can also remove the parenthesis:
int min = x < y ? x < z ? x : z : y < z ? y : z;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With