该程序使用三元运算符找到三个数中最大的一个。在完成程序之前,让我们了解什么是三元运算符:
三元运算符计算一个布尔表达式并根据结果赋值。
variable num = (expression) ? value if true : value if false
如果表达式结果为true,则将冒号(:)之前的第一个值赋给变量num,否则将第二个值赋给num。
示例:使用三元运算符编程以查找最大数字
在本程序中,我们使用三元运算符两次来比较这三个数字,但是您可以使用三元运算符比较一个语句中的所有三个数字,如下所示:
result = num3 > (num1>num2 ? num1:num2) ? num3:((num1>num2) ? num1:num2);
但是,如果您发现难以理解,那么请使用它,就像我在下面的示例中所示:
import java.util.Scanner;public class JavaExample{public static void main(String[] args){int num1, num2, num3, result, temp;/* Scanner is used for getting user input.* The nextInt() method of scanner reads the* integer entered by user.*/Scanner scanner = new Scanner(System.in);System.out.println("Enter First Number:");num1 = scanner.nextInt();System.out.println("Enter Second Number:");num2 = scanner.nextInt();System.out.println("Enter Third Number:");num3 = scanner.nextInt();scanner.close();/* In first step we are comparing only num1 and* num2 and storing the largest number into the* temp variable and then comparing the temp and* num3 to get final result.*/temp = num1>num2 ? num1:num2;result = num3>temp ? num3:temp;System.out.println("Largest Number is:"+result);}}
输出:
Enter First Number:89Enter Second Number:109Enter Third Number:8Largest Number is:109
