die*_*lar 0 java ternary-operator conditional-statements
我知道三元运算符用于在评估逻辑条件后进行变量赋值.
所以:
String s = (logicalVariable) ? "Hello" : "Bye, bye";
Run Code Online (Sandbox Code Playgroud)
要么,
int x = (5<3) ? 10 : 100;
Run Code Online (Sandbox Code Playgroud)
将是用法示例,对吧?
但是,如果我真的不想做变量赋值但是设置一个句子甚至一段代码,例如:
if (inventario.containsKey(item))
return inventario.get(item);
else return Integer.MIN_VALUE;
Run Code Online (Sandbox Code Playgroud)
可以使用三元运算符将这些行写成一行表达式吗?
这应该工作:
return inventario.containsKey(item)? inventario.get(item); Integer.MIN_VALUE;
Run Code Online (Sandbox Code Playgroud)
第一部分只需要评估一个 boolean
return inventario.containsKey(item) ? inventario.get(item) : Integer.MIN_VALUE;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
72 次 |
| 最近记录: |