假设我们有以下if语句:
int a = 1;
int b = 2;
if(a < b) {
System.out.println("A is less than B!");
}
else {
System.out.println("A is greater or equal to B!");
}
我一直在想,如果if语句由if语句由每个子块(if和else块)中的一行代码组成,那么三元运算符是否会替换if语句,那么为什么上面的示例无法用三元运算符这样写呢?
(a < b) ? System.out.println("A is less than B!") : System.out.println("A is greater or equal to B!");
您只能? :
用于表达式,不能用于语句。尝试
System.out.println(a < b ? "A is less than B!" : "A is greater or equal to B!");
注意:这也更短/更简单。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句