Java Program to Find Smallest of Three Numbers Using Ternary Operator

24 Dec 2024 | 阅读 4 分钟

在本节中,我们将学习如何创建一个 Java 程序来查找三个数字中的最小数。除此之外,我们还将学习如何在 Java 中使用三元运算符查找三个数字中的最小数

使用三元运算符

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

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

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

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

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

SmallestNumberExample1.java

输出

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

我们也可以在单个语句中使用三元运算符来比较所有三个数字。如果我们想在单个语句中比较三个数字,应使用以下语句:

在以下程序中,我们使用了单个语句来查找三个数字中的最小数。

SmallestNumberExample2.java

输出

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

使用 if-else..if

SmallestNumberExample3.java

输出

8 is the smallest number

使用嵌套 if 语句

SmallestNumberExample4.java

输出

The smallest number is: 169

让我们看看查找三个数字中最小数的另一种逻辑。

SmallestNumberExample5.java

输出 1

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

输出 2

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