简短的 IF-ELSE 语句

我试图让我的代码更具可读性,所以我决定使用一些简短的 IF 语句。

下面是我的代码,它不起作用(“不是一个语句”) :

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

这个有什么问题吗? 需要括号吗? 在哪里?

430687 次浏览
jXPanel6.setVisible(jXPanel6.isVisible());

or in your form:

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

The ternary operator can only be the right side of an assignment and not a statement of its own.

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

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

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

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

It's not really meant to be used as a short, in-line if-else. In particular, you can't use it if the individual parts don't return a value, or return values of incompatible types. (So while you could do this if both method happened to return the same value, you shouldn't invoke it for the side-effect purposes only).

So the proper way to do this would just be with an if-else block:

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

which of course can be shortened to

jXPanel6.setVisible(jXPanel6.isVisible());

Both of those latter expressions are, for me, more readable in that they more clearly communicate what it is you're trying to do. (And by the way, did you get your conditions the wrong way round? It looks like this is a no-op anyway, rather than a toggle).

Don't mix up low character count with readability. The key point is what is most easily understood; and mildly misusing language features is a definite way to confuse readers, or at least make them do a mental double-take.

As others have indicated, something of the form

x ? y : z

is an expression, not a (complete) statement. It is an rvalue which needs to get used someplace - like on the right side of an assignment, or a parameter to a function etc.

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

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

From what i can tell, you're just wanting to toggle the visibility state right? Why not just use the ! operator?

jxPanel6.setVisible(!jxPanel6.isVisible);

It's not an if statement but I prefer this method for code related to your example.

You can do it as simple as this, I did it in react hooks :

 (myNumber == 12) ? "true" : "false"

it was equal to this long if function below :

if (myNumber == 12) {
"true"
} else {
"false"
}

Hope it helps ^_^