Java 三元运算符也称为条件运算符。三元运算符主要用于决策过程以返回 true 或 false。它根据给定表达式的结果返回语句。此编程中条件或三元运算符的基本语法如下所示
Test_expression ? statement1: statement2
如果给定的测试条件或布尔表达式评估为 true,则条件运算符将返回 statement1。如果条件评估为 false,则返回 statement2。
Java 三元运算符示例
在此程序中,我们将使用三元或条件运算符来确定此人是否符合投票条件。
import java.util.Scanner;
public class Example {
private static Scanner sc;
public static void main(String[] args) {
int age;
sc = new Scanner(System.in);
System.out.println(" Please Enter Your Age: ");
age = sc.nextInt();
String Message = (age >= 18)? " You are eligible to Vote " :
" You are Not eligible to Vote ";
System.out.println(Message);
/** REPLACE THE ABOVE CODE WITH FOLLOWING CODE
* System.out.println((age >= 18)?
* " You are eligible to Vote":
* "You are Not eligible to Vote");
*/
}
}
此 Java 三元条件运算符程序允许用户输入年龄并将用户输入的整数值分配给 age 变量。如果用户输入的值为 18 或以上,它会将 ? 符号后的第一个语句分配给字符串变量 Message。“您有资格投票。”
如果用户输入低于 18,则第二个语句(: 符号后)将分配给字符串变量 Message。“您没有资格投票。”
最后,我们使用 System.out.println 语句打印 Message 变量中的字符串数据。
Please Enter Your Age:
15
You are Not eligible to Vote
让我们尝试不同的值
Please Enter Your Age:
29
You are eligible to Vote
Java 嵌套三元或条件运算符示例
在此程序中,我们将使用嵌套三元运算符来查找此人是否符合工作条件。
- 在此三元运算符示例中,我们声明了一个名为 Message 的字符串变量,并将此变量分配给条件功能。
- 第一个条件检查年龄是否小于 18。如果此条件为 True,它将返回 ? 符号后的第一个值,即“您太年轻,无法工作”
- 当第一个条件失败时,它将执行 : 符号后的变量。通过使用嵌套条件运算符,我们在此处检查另一个条件 (age >= 18 && age <= 60)。如果此条件为 True,它将返回 ? 符号后的第一个值,即“您有资格工作”
- 如果条件的嵌套条件失败,三元运算符将执行 : 符号后的变量,即“您太老了,无法工作”。
import java.util.Scanner;
public class ConditionalOperator {
private static Scanner sc;
public static void main(String[] args) {
int age;
sc = new Scanner(System.in);
System.out.println(" Please Enter Your Age: ");
age = sc.nextInt();
String Message = (age < 18)? " You are too Young to Work " :
(age >= 18 && age <= 60)? " You are eligible to Work ":
" You are too Old to Work ";
System.out.println(Message);
}
}

Java 输出 2
Please Enter Your Age:
28
You are eligible to Work
Please Enter Your Age:
65
You are too Old to Work