JAVA 使用三元运算符调用方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12643973/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:40:20  来源:igfitidea点击:

JAVA calling a method using a ternary operator

javaternary

提问by Trae Moore

I am trying to use ? to decide which method i want to call, but i do not need to assign a variable. My question: Is there a way to use the ternary operator with out assigning a variable?

我正在尝试使用 ? 决定我想调用哪个方法,但我不需要分配变量。我的问题:有没有办法在不分配变量的情况下使用三元运算符?

(something i dont need) = (x == 1)? doThisMethod():doThatMethod()

instead of

代替

if(x == 1) {
    doThisMethod()
} else {
    doThatMethod()
}

回答by Kevin DiTraglia

This will not work, as it is not the intended use of the ternary operator.

这将不起作用,因为它不是三元运算符的预期用途。

If you really want it to be 1 line, you can write:

如果你真的希望它是 1 行,你可以写:

if (x==1) doThisMethod(); else doThatMethod();

回答by Lukas Eder

I doubt that this works. The JLS §15.25defines the ternary expression as follows:

我怀疑这是否有效。所述JLS§15.25定义三元表达如下:

ConditionalExpression:
    ConditionalOrExpression
    ConditionalOrExpression ? Expression : ConditionalExpression

And a ConditionalExpressionisn't a Statementby itself. It can be used in various other places, though, e.g. an Assignment:

而且 a本身ConditionalExpression并不是 a Statement。但是,它可以在其他各种地方使用,例如Assignment

AssignmentExpression:
    ConditionalExpression
    Assignment

Assignment:
    LeftHandSide AssignmentOperator AssignmentExpression

回答by ruakh

According to §14.8 "Expression Statements" of the Java Language Specification, the only expressions that can be used alone as statements are:

根据Java Language Specification 的§14.8 "Expression Statements",唯一可以单独用作语句的表达式是:

  • assignments
  • pre– and post-increments and pre– and post-decrements
  • method calls
  • class instance creation expressions (constructor calls)
  • 作业
  • 前后递增和前后递减
  • 方法调用
  • 类实例创建表达式(构造函数调用)

回答by Mightian

Much more diversified, if the flow was to break after the method call.this can be used, but a word of caution if the flow does not break after the if then both methods will get executed.

更加多样化,如果流程在方法调用后中断。这可以使用,但是如果流程在 if 之后没有中断,那么两个方法都将被执行。

if (x==1) 
doThisMethod();
doThatMethod();