vendredi 19 juillet 2019

Can we use '?' operator instead of nested-if condition?

A nested-if condition to be written using the ? : syntax. Is it not an allowed scenario?

Below is the code

public class ControlFlow{

    public static void main(String args[]){

        int i=(10>5)?(2<5)?230:456;
        System.out.println("i="+i);

    }
}

My idea was that first 10>5 would be evaluated, and as it is true, it would then verify if 2<5 or not. Now since that is also true, "i" should be assigned to 230. The error message was

ControlFlow.java:10: error: : expected
        int i=(10>5)?(2<5)?230:456;

ControlFlow.java:10: error: ';' expected
        int i=(10>5)?(2<5)?230:456;
                                   ^
ControlFlow.java:11: error: illegal start of expression
        System.out.println("i="+i);
              ^
ControlFlow.java:11: error: ';' expected
        System.out.println("i="+i);

Aucun commentaire:

Enregistrer un commentaire