简体   繁体   中英

Short java if else if else statement

I have a if else short statement as follows:

(one == two) ? "do this" : "do this"

Is there anyway to add an if else into this statement?

I can't seem to find anything with an if else...

I'm being specific to the short statement, as opposed to do if if else else longhand.

Thanks.

You can extend this to any number of clauses, in perfect analogy to the if-else construct.

return a == b? "b"
     : a == c? "c"
     : a == d? "d"
     : "x";

In this form it quite closely resembles Lisp's cond , both in shape and in semantics.

But, do note that this is not a "shorthand for if/else" because it is an expression whereas if/else is a statement . It would be quite bad abuse of the ternary operator if the expressions had any side effects.

If you want to convert something like:

if(A) {
    return X;
}
else if(B) {
    return Y;
}
else {
    return Z;
}

You can write this as:

A ? X : (B ? Y : Z);

You thus write the else if as a condition in the else -part (after : ) of the upper expression.

However, I would strongly advice against too much cascading. The code becomes extremely unreadable and the ? : ? : code structure was never designed for this.

The ":" is the else

(one == two) ? "do this" : "do that"

If one equals two then "do this", otherwise (if one not equals two) than "do that".

I sometimes use Maps for such situations:

private final static Map <String, String> codesMap = <generate the map with values>
...
codesMap.get(one)

Yes, Above statement can be written using if-else. Here Ternary operator is used.

if(one==two)
 {
    //Code
 }
else
 {
    //code
 }

Ternary operator reduces Line Of Code(LOC) by writing condition in one statement instead of many using "? :".

For more information please refer:

http://java.meritcampus.com/t/48/Ternary-operator?tc=mm71

http://java.meritcampus.com/t/60/If-else-if-ladder?tc=mm72

This works like an if-else-statement but technically you could convert this into an if-else-statement . That would look like this:

if (one == two) {
"do this"
} else {
"do that"
}

if your question is whether or not you could insert an if statement into (one == two) ? "do this" : "do this" (one == two) ? "do this" : "do this" ... no, rather you should use nested if statements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM