Java Program to Find Largest of Three Numbers

17 Mar 2025 | 4 分钟阅读

在本节中,我们将学习如何创建一个 Java 程序来查找三个数字中的最大值。同时,我们还将学习使用三元运算符在 Java 中查找三个数字中的最大值。

使用三元运算符

在开始编程之前,让我们先了解一下三元运算符。

它是Java 条件语句的一部分。它包含三个操作数。它评估一个布尔表达式,并根据结果分配一个值。我们可以用它来代替if-else 语句。三元运算符的语法如下:

如果上述表达式返回true,则冒号之前的值赋给变量variable_name,否则冒号之后的值赋给该变量。

让我们在 Java 程序中使用三元运算符来比较三个变量。

在下面的程序中,我们使用了两个三元运算符来比较三个数字。

LargestNumberExample1.java

输出

Enter the first number:
23
Enter the second number:
11
Enter the third number:
67
Largest Number is: 67

我们也可以使用三元运算符在一行语句中比较这三个数字。如果我们想在一行语句中比较三个数字,我们必须使用以下语句。

在下面的程序中,我们使用了一个单独的语句来查找三个数字中的最大值。

LargestNumberExample2.java

输出

Enter the first number:
45
Enter the second number:
87
Enter the third number:
34
The largest number is: 87

使用 if-else..if

LargestNumberExample3.java

输出

78 is the largest number

使用嵌套 if

LargestNumberExample4.java

输出

The largest number is: 1010

LargestNumberExample5.java

输出 1

Enter three integers: 
12 110 9
The largest number is: 110

输出 2

Enter three integers: 
9 9 9
The numbers are same.