Multiple conditions in ternary operators
Asked Answered
H

14

22

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?

Hargrave answered 13/2, 2011 at 20:26 Comment(4)
try it but instead of the last test, just put ":z"Suspensory
At least in my experienced, just because you can write chained ternary statements, doesn't mean you should. Also, what you have so far is very complicated, you should only need to compare the variables to one another once: int smallest = min(min(x, y), z).Deteriorate
Math.min uses the ternary operator. the simplest is to staticly import this method and write smalledNum = min(x, min(y, z))Strapper
Consider modifying the assignment for the likely event when the professor makes "three" a variable. This will likely get you extra credit.Dehisce
D
36

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;
Decern answered 13/2, 2011 at 20:32 Comment(2)
Parentheses-free version looks like an entry to Obfuscated-C competition.Figment
Why does adding extra paranthesis gives error: unexpected type int min = x < y ? ((x < z) ? x : z) : ((y < z) ? y : z);Postcard
J
14

Since this is homework I'm not just going to give you the answer, but instead an algorithm so that you can work it out yourself.

First work out how to write min(x, y) using a single ternary operator.

Once you have that, change the following code for min(x, y, z) to use a ternary operator then substitute in the code for min(x, y) that you worked out from the previous step.

int min(x, y, z) {
    if (x <= y) {
        return min(x, z);
    } else {
        return min(y, z);
    }
}
Johnie answered 13/2, 2011 at 20:32 Comment(0)
I
5

You're testing for z, when you really don't need to. Your ternary operator must be of form cond ? ifTrue : ifFalse;

so if you have multiple conditions, you have this:

cond1? ifTrue1 : cond2? if True2 : ifFalse2;

If you understand this, don't look below. If you still need help, look below.

I also included a version that doesn't nest them that is clearer (assuming you don't need to have them nested. I sure would hope your assignment doesn't require you to nest them because that's pretty ugly!)

.

.

Here's what I come up with:

class QuestionNine
{
    public static void main(String args[])
    {
        smallest(1,2,3);
        smallest(4,3,2);
        smallest(1,1,1);
        smallest(5,4,5);
        smallest(0,0,1);
    }

    public static void smallest(int x, int y, int z) {
        // bugfix, thanks Mark! 
        //int smallestNum = (x<y && x<z) ? x : (y<x && y<z) ? y :  z;
        int smallestNum = (x<=y && x<=z) ? x : (y<=x && y<=z) ? y :  z;
        System.out.println(smallestNum + " is the smallest of the three numbers.");
    }

    public static void smallest2(int x, int y, int z) {
       int smallest = x < y ? x : y; // if they are equal, it doesn't matter which
       smallest = z < smallest ? z : smallest;
       System.out.println(smallest + " is the smallest of the three numbers.");
    }
}
Ingrown answered 13/2, 2011 at 20:34 Comment(0)
D
2
public static int min(int x, int y, int z) {
    return x<y?Math.min(x, z):Math.min(y, z);           
}

public static void main(String[] args) {
    int smallestNum = min(10, 12, 15);
    System.out.println(smallestNum);
}
Delectate answered 13/2, 2011 at 23:49 Comment(1)
I like this implementation. Let the libraries do the workFriulian
E
2

I know it's late. Just for information this also works:

int smallestNum = (x<y ? x : (x=y)) < z ? x : z
Eskew answered 18/6, 2015 at 20:59 Comment(1)
It's mutating the data, though, but I can see this workingChalybeate
L
1

The last part: (z<y && z<x) ? z is missing a ':' :

(z<y && z<x) ? z : some_value;
Lowndes answered 13/2, 2011 at 20:32 Comment(0)
B
1

My solution:

public static void main(String args[])
{
    int x = 1, y = 2, z = 3;
    int smallestNum = (x < y && x < z) ? x :
        (y < x && y < z) ? y :
        (z < y && z < x) ? z:y;
    System.out.println(smallestNum + " is the smallest of the three numbers.");
}
Bremerhaven answered 23/4, 2012 at 3:14 Comment(0)
I
1

My contribution ...

public static int getSmallestNumber( int x, int y, int z) {

     return x < y && x < z ? x : y < x && y < z ? y : z;
}

public static void main ( String ... args ) {

    System.out.println( getSmallestNumber( 123, 234, 345 ) );
}
Inhospitable answered 3/11, 2012 at 1:58 Comment(2)
Returns 2 when it is called with parameters (3,2,1)Phylloxera
@Phylloxera ~ Good Catch... Fixed.Inhospitable
N
1
public static void main(String args[]) {
    Scanner sc=new Scanner(System.in);
    System.out.println("enter the number and check heigest number of three number:-");
    int a=sc.nextInt();
    int b=sc.nextInt();
    int c=sc.nextInt();
    int max;
    max=(a>b&&a>c)?a:(b>a&&b>c)?b:(c>a&&c>b)?c:(a==b&&b==c)?a:0;
    
    System.out.println("the heigest number is:"+max);
    
Nekton answered 28/7, 2021 at 10:25 Comment(0)
C
0

This answer is coming in seven years late, so I'll just give you the code:

int smallestNumber = (x > y) ? 
            ((y > z) ? z : y) : 
            ((x > z) ? z : x);

The indentation should explain the code, which is simply a ternary that evaluates other ternaries on the initial condition x > y; /* the first ternary gets evaluated if that condition is true, else the second one gets evaluated. */

Chalybeate answered 31/1, 2018 at 21:52 Comment(0)
F
0

you missed the value after z var smallestNum = (x<y && x<z) ? x : (y<x && y<z) ? y : (z<y && z<x) ? z:0; Try this, it works

Faints answered 31/10, 2020 at 17:1 Comment(0)
J
0
public class questionNine{
  public static void main(String args[]){
    int x = 1, y = 2, z = 3;
    int smallestNum =  (x<y && x<z) ? x : ((y < x && y<z) ? y : z);
    System.out.println(smallestNum);
  }
}
Jokester answered 1/2, 2022 at 11:45 Comment(0)
M
-1
int min = (x<y)?((x<z)?x:z):((y<z)?y:z);
Meissner answered 13/2, 2011 at 20:36 Comment(0)
G
-1

best way to do this is to make an example using if and else statement and then apply the ternary operators on it (q

Graminivorous answered 22/2, 2014 at 7:1 Comment(1)
Please add some more details in your answerDeform

© 2022 - 2024 — McMap. All rights reserved.