English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在本文中,您将学习使用条件或三元运算符来更改程序的控制流。
在学习三元运算符之前,您需要了解Java中的if ... else语句。三元运算符可用于替换简单的 if...else 语句。例如,
You can replace the following code
if (expression) { number = 10; } else { number = -10; }
Is equivalent to:
number = (expression) ? expressionTrue : expressinFalse;
为什么命名三元运算符?因为它使用3个操作数。
这里 expression 是一个布尔表达式,其结果为true 或 false。如果为true,expressionTrue则被评估并分配给变量number。如果为False,expressionFalse则被评估并分配给变量number。
class Operator { public static void main(String[] args) { Double number = -5.5; String result; result = (number > 0.0) ? "正数" : "非正数"; System.out.println(number + " is " + result); } }
When running the program, the output is:
-5.5 is not a positive number
You can use the ternary operator to replace multi-line code with a single line code. It makes your code more readable. However, do not overuse the ternary operator. For example,
You can replace the following code
if (expression1) { result = 1; } result = 2; } result = 3; } result = 0; }
Is equivalent to:
result = (expression1) ? 1 : (expression2) ? 2 : (expression3) ? 3 : 0;
In this case, the use of the ternary operator makes the code difficult to understand.
Use the ternary operator only when the result statement is short. This will make your code clear and easy to understand.