I would like to print:
Permissive mode: ON
or
Permissive mode: OFF
I was trying to do it in one line like this:
logMessage("Permissive mode: " + (isPermissive == true) ? "ON" : "OFF" );
I could do full if/else statement and a separate variable for ON/OFF but was trying to keep it short...
只需使用
logMessage("Permissive mode: " + ((isPermissive) ? "ON" : "OFF"));
You need parentheses around the conditional assignment operator ? :
? :
because there's an addition operator before it, and +
has a higher precedence than ? :
? :
.
Without the parentheses, "Permissive mode: " + (isPermissive == true) ? "ON" : "OFF"
"Permissive mode: " + (isPermissive == true) ? "ON" : "OFF"
is equivalent to ("Permissive mode: " + (isPermissive == true)) ? "ON" : "OFF"
("Permissive mode: " + (isPermissive == true)) ? "ON" : "OFF"
The result of the +
addition operator with String operands isn't a boolean
, so the compiler will complain rightfully on the expression.
You need to surround the operator with less precedence with parentheses if you want it to evaluate first:
logMessage("Permissive mode: " + (isPermissive ? "ON" : "OFF") );
You can factorize it with a new method, wrapping logMessage:
public void myLogMessage(String message, boolean flag) {
logMessage(message + ": " + (flag ? "ON" : "OFF"));
}
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.