[英]How can I simplify this if-else into one statement?
How can I simplify the following code to one line (without the if-else
statement)? 如何将以下代码简化为一行(没有if-else
语句)?
public static void main(String[] args)
{
boolean result;
boolean a = false;
boolean b = false;
boolean isEmpty = false;
if (a) {
result = isEmpty && !b;
System.out.println("if " + (isEmpty && !b));
} else {
System.out.println("else " + !b);
result = !b;
}
System.out.println(result);
}
If a
is true
, you must check that isEmpty
AND !b
are both true
. 如果a
为true
,则必须检查isEmpty
AND !b
是否为true
。 If a
is false
(or !a
is true
), it's enough to check that !b
is true
. 如果a
为false
(或者!a
为true
),则足以检查!b
是否为true
。
Therefore you can replace the logic of the if statement with: 因此,您可以使用以下命令替换if语句的逻辑:
result = !b && (isEmpty || !a);
您可以使用三元运算符:
result = a ? isEmpty && !b : !b;
I think that what you are searching for is the ternary operator 我认为你正在寻找的是三元运算符
In fact, you could summarize that if-else statement with something like this (but without the println): 事实上,你可以用这样的东西(但没有println)总结if-else语句:
result = (a ? isEmpty && !b : !b); System.out.println(result + "\\n");
使用以下内容:
result = a ? isEmpty && !b : !b;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.