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?
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;