IF Short Expression - ELSE

I am trying to make my code more readable, so I decided to use a few short IF statements.

Here is my code that does not work ("no expression"):

jXPanel6.isVisible() ? jXPanel6.setVisible(true) : jXPanel6.setVisible(false); 

What happened to this? Need brackets? Where?

+59
java if-statement
Dec 16 '10 at 14:50
source share
5 answers

The terminal expression x ? y : z x ? y : z can only be used for conditional assignment. That is, you can do something like:

 String mood = inProfit() ? "happy" : "sad"; 

because the ternary expression returns something (of type String in this example).

It is not intended to be used as a short, built-in if-else . In particular, you cannot use it unless the individual parts return a value or return values ​​of incompatible types. (Thus, although you could do this if both methods returned the same value, you should not call it only for side effects).

Thus, the correct way to do this would only be with an if-else block:

 if (jXPanel6.isVisible()) { jXPanel6.setVisible(true); } else { jXPanel6.setVisible(false); } 

which of course can be reduced to

 jXPanel6.setVisible(jXPanel6.isVisible()); 

Both of these last expressions are more readable to me in that they more clearly indicate what exactly you are trying to do. (And, by the way, you did not accidentally change your conditions? It seems that this is not an operation, not a switch).

Do not mix the number of characters with readability. The key point is what is most easily understood; and gently abuse language features is a definite way to confuse readers, or at least get them to do a mental double take.

+179
Dec 16 2018-10-16
source share
 jXPanel6.setVisible(jXPanel6.isVisible()); 

or in your form:

 jXPanel6.setVisible(jXPanel6.isVisible()?true:false); 
+27
Dec 16 '10 at 14:51
source share

The ternary operator can only be the right part of the task, and not its own expression.

http://www.devdaily.com/java/edu/pj/pj010018/

+4
Dec 16 '10 at 14:51
source share

As others pointed out, something like a form

 x ? y : z 

is an expression, not a (complete) statement. This is the rvalue value that needs to be used somewhere - for example, on the right side of the task or a parameter for a function, etc.

Maybe you could look at this: http://download.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html

+3
Dec 16 2018-10-16
source share

I'm a little late to the party, but to future readers.

From what I can say, you just want to switch the visibility state correctly? Why not just use the operator ! ?

 jxPanel6.setVisible(!jxPanel6.isVisible); 

This is not an if statement, but I prefer this method for the code associated with your example.

+2
May 10 '15 at 12:52
source share



All Articles