Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple conditions in ternary operators

Tags:

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?

like image 562
Mike Avatar asked Feb 13 '11 20:02

Mike


People also ask

Can a ternary operator have multiple conditions?

We can nest ternary operators to test multiple conditions.

Can ternary operator have 3 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.


1 Answers

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;
like image 135
Markus Johnsson Avatar answered Oct 25 '22 08:10

Markus Johnsson