在单行中分配和执行 if/else 条件

assign and execute if/else conditions in single line

我该怎么做,例如,if 块检查条件是 true 还是 false,然后根据该条件执行操作?

喜欢,

if (check true or false) 
         if false do action
         if true do action

类似的事情在没有块的同一行中完成,这可能吗?

抱歉我的英语不好

谢谢。

如果您真的非常需要单行代码,您可以使用此语法(称为三元运算符):

1>0 ? "do action" : " Do other action";

例如:

String result = x>y ? "x>y" : "y>x";

但不推荐这样做,大多数人讨厌这种语法,因为如果你在其中级联多个条件,甚至是最糟糕的级联三元运算符,它会变得非常不可读。

但它有它的用途。

也许 ternary operator 可以满足您的要求:

checkIfTrue() ? actionIfTrue() : actionIfFalse();

您可以使用三元运算符:

if(condition) ? executeForTrue() : executeForFalse();

我想这几乎可以满足您的需求。

max = (a > b) ? a : b;

在逻辑上等同于

if (a > b) {
    max = a;
} else { max = b; }

您可以使用java ternary operator,

result = testCondition ? value1 : value2

这条语句可以理解为,如果testCondition为真,将value1的值赋给result;否则,将 value2 的值赋给 result.

简单的例子是,

minVal = a < b ? a : b;

上面代码中,如果变量a小于b,则minVal赋值为a;否则,minVal 被赋予 b 的值。

这是另一个使用 String

的示例
// result is assigned the value "it's false"
String result = false ? "that was true" : "it's false";

这个例子会更清楚。它会根据一个人的性别正确打印称呼:

// if `person.isMale()` then its Mr. else its Ms. 
return = "Thank you " + (person.isMale() ? "Mr. " : "Ms. ") + person.getLastName() + ".";

编辑:

Question: you cannot call a method inside ternary operator.

不,这是不正确的。

您可以在三元运算符中调用方法,只要它 returns 的值与三元运算符左侧的类型相同,

考虑这个例子,

让我们创建一个 returns 一个 String 值的方法,

String message(){
    return "This is returned value";
}

现在看到这段代码,

String answer = false ? "true" : message();

这将执行得很好,因为 message()return 类型和 answer 的变量类型相同,即 String.

输出:

This is returned value

您不能使用三元运算符,因为您不能从 Ternary Operator[ 调用任何 void 方法(即不 return 任何东西的方法) =12=]

因为它不是 三元运算符 的预期用途。

如果实在想在1行内实现,可以这样写:

if (condition) doThisMethod(); else doThatMethod();

要将条件语句放在一行中,您可以使用三元运算符。但是请注意,这只能用于 assignments,即如果函数实际上 return 某些东西并且您想将该值分配给变量。

int abs = x > 0 ? x : -1; 

如果你想执行不return任何东西但有一些其他副作用的方法,三元运算符不是正确的方法。事实上,它甚至无法编译!

void doThis() {/* do this */}
void doThat() {/* do that */}

(condition) ? doThis() : doThat();  // does not work!

相反,您应该使用普通的 if-then-else。它也更易于阅读。

if (condition) {
    doThis();
} else {
    doThat();
}