简体   繁体   English

如何使用if / else快捷方式根据布尔值打印字符串

[英]How do I use if/else shortcut to print string based on boolean value

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... 我可以做完整的if / else语句,并为ON / OFF设置一个单独的变量,但试图使其简短一些...

只需使用

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" "Permissive mode: " + (isPermissive == true) ? "ON" : "OFF"

is equivalent to ("Permissive mode: " + (isPermissive == true)) ? "ON" : "OFF" 等价于("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. 所述的结果+与字符串的操作数的加法运算符是不是一个boolean ,所以编译器将理所当然抱怨上的表达。

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: 您可以使用包装logMessage的新方法对其进行分解:

public void myLogMessage(String message, boolean flag) {
    logMessage(message + ": " + (flag ? "ON" : "OFF"));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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