在 Java 中,三元 运算符 可以在某些情况下用来替代 if…else
语句。在学习三元运算符之前,请确保您已访问 Java if...else 语句。
Java 中的三元运算符
三元运算符会评估测试条件,并根据条件的结果执行一段代码。
其语法为
condition ? expression1 : expression2;
这里,会评估 condition,并且
- 如果 condition 为
true
,则执行 expression1。 - 如果 condition 为
false
,则执行 expression2。
三元运算符需要 **3 个操作数**(condition、expression1 和 expression2)。因此,名称为 **三元运算符**。
示例:Java 三元运算符
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// take input from users
Scanner input = new Scanner(System.in);
System.out.println("Enter your marks: ");
double marks = input.nextDouble();
// ternary operator checks if
// marks is greater than 40
String result = (marks > 40) ? "pass" : "fail";
System.out.println("You " + result + " the exam.");
input.close();
}
}
输出 1
Enter your marks: 75 You pass the exam.
假设用户输入 **75**。那么,条件 marks > 40
评估为 true
。因此,第一个表达式 "pass"
被赋给 result。
输出 2
Enter your marks: 24 You fail the exam.
现在,假设用户输入 **24**。那么,条件 marks > 40
评估为 false
。因此,第二个表达式 "fail"
被赋给 result。
注意:要了解表达式,请访问 Java 表达式。
何时使用三元运算符?
在 Java 中,三元运算符可以用来替代某些类型的 if...else
语句。例如,
您可以将此代码替换为
class Main {
public static void main(String[] args) {
// create a variable
int number = 24;
if(number > 0) {
System.out.println("Positive Number");
}
else {
System.out.println("Negative Number");
}
}
}
替换为
class Main {
public static void main(String[] args) {
// create a variable
int number = 24;
String result = (number > 0) ? "Positive Number" : "Negative Number";
System.out.println(result);
}
}
输出
Positive Number
这里,两个程序给出相同的输出。但是,使用三元运算符使我们的代码更具可读性和简洁性。
注意:只有当结果语句较短时,才应使用三元运算符。
嵌套的三元运算符
在一个三元运算符中嵌套另一个三元运算符也是可能的。这在 Java 中称为嵌套三元运算符。
这是一个使用嵌套三元运算符查找 **3** 个数字中最大值的程序。
class Main {
public static void main(String[] args) {
// create a variable
int n1 = 2, n2 = 9, n3 = -11;
// nested ternary operator
// to find the largest number
int largest = (n1 >= n2) ? ((n1 >= n3) ? n1 : n3) : ((n2 >= n3) ? n2 : n3);
System.out.println("Largest Number: " + largest);
}
}
输出
Largest Number: 9
在上面的示例中,请注意三元运算符的使用,
(n1 >= n2) ? ((n1 >=n3) ? n1 : n3) : ((n2 >= n3) ? n2 : n3);
这里,
(n1 >= n2)
- 第一个测试条件,检查 n1 是否大于 n2(n1 >= n3)
- 如果第一个条件为true
,则执行第二个测试条件(n2 >= n3)
- 如果第一个条件为false
,则执行第三个测试条件
注意:不建议使用嵌套的三元运算符。因为这会使我们的代码更复杂。