Java 如果没有 else 三元运算符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20053257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
If without else ternary operator
提问by Z.V
So far from I have been searching through the net, the statement always have if and else condition such as a ? b : c
. I would like to know whether the if
ternary statement can be used without else
.
Assuming i have the following code, i wish to close the PreparedStatement
if it is not null
到目前为止,我一直在网上搜索,该语句始终具有 if 和 else 条件,例如a ? b : c
. 我想知道if
三元语句是否可以在没有else
. 假设我有以下代码,PreparedStatement
如果它不为空,我希望关闭
(I am using Java programming language.)
(我正在使用 Java 编程语言。)
PreparedStatement pstmt;
//....
(pstmt!=null) ? pstmt.close : <do nothing>;
采纳答案by frankie liuzzi
回答by Jeroen Vannevel
Just write it out?
直接写出来?
if(pstmt != null) pstmt.close();
It's the exact same length.
这是完全相同的长度。
回答by cigno5.5
Why using ternary operator when you have only one choice?
当您只有一种选择时,为什么要使用三元运算符?
if (pstmt != null) pstmt.close();
is enough!
足够!
回答by Yegoshin Maxim
回答by David M?rtensson
A ternary operation is called ternary beacause it takes 3 arguments, if it takes 2 it is a binary operation.
三元运算称为三元运算,因为它需要 3 个参数,如果它需要 2 个参数,则它是一个二元运算。
And as noted above, it is an expressionreturning a value.
如上所述,它是一个返回值的表达式。
If you omit the else you would have an undefined situation where the expression would not return a value.
如果省略 else ,则会出现未定义的情况,即表达式不会返回值。
So as also noted in other answer, you should use an if statement.
因此,正如其他答案中所述,您应该使用 if语句。
回答by Krease
As mentioned in the other answers, you can't use a ternary operator to do this.
正如其他答案中所述,您不能使用三元运算符来执行此操作。
However, if the need strikes you, you can use Java 8 Optionaland lambdas to put this kind of logic into a single statement:
但是,如果需要,您可以使用 Java 8 Optional和 lambdas 将这种逻辑放入单个语句中:
Optional.of(pstmt).ifPresent((p) -> p.close())
回答by WesternGun
You cannot use ternary without else, but to do a "if-without-else" in one line, you can use Java 8 Optional
class.
您不能在没有 else 的情况下使用三元,但要在一行中执行“if-without-else”,您可以使用 Java 8Optional
类。
PreparedStatement pstmt;
//....
Optional.ofNullable(pstmt).ifPresent(pstmt::close); // <- but IOException will still happen here. Handle it.
回答by bluejayke
Well in JavaScript you can simply do:
在 JavaScript 中,您可以简单地执行以下操作:
expression ? doAction() : undefined
since that's what's literally actually happening in a real if statement, the else clause is simply undefined. I image you can do pretty much the same thing in (almost?) any programming language, for the else clause just put a null-type variable that doesn't return a value, it shouldn't cause any compile errors.
因为那是真正的 if 语句中实际发生的事情,所以 else 子句只是未定义的。我想象你可以在(几乎?)任何编程语言中做几乎相同的事情,因为 else 子句只是放置一个不返回值的空类型变量,它不应该导致任何编译错误。