Java 程序:查找三个数字中的最小值


2022年4月13日, Learn eTutorial
2994

为了实现一个 Java 程序来找出三个数字中的最小值,我们需要从用户那里读取三个整数,然后使用 if-else 语句来找出最小的数字。

如何使用 Java 程序找出三个数字中的最小值?

首先,我们必须声明类 SmallestNumber。现在我们需要声明变量 'a'、'b'、'c' 来保存三个整数。然后使用扫描器类对象从用户那里读取数字。使用 if 条件检查 'a' 是否小于 'b' 和 'c',如果是,则打印 'a' 是最小值。否则检查 'b' 是否小于 'c',如果是,则打印 'b' 是最小值。最后,如果这些条件都不满足,则打印 'c'。

算法

步骤 1: 将类 Smallest 声明为 public。

步骤 2:打开 main() 以启动程序,Java 程序执行从 main() 开始

步骤 3: 声明整数变量 a,b,c

步骤 4: 创建扫描器类对象 sc

步骤 5: 将三个数字读取到变量 a,b,c 中。

步骤 6: 检查 a

步骤 7: 打印最小的数字是 a

步骤 7: 否则检查 b < c,如果为真,则显示最小的数字为 b

步骤 8: 否则显示最小的数字是 c


 

Java 源代码

                                          import java.util.Scanner;
public class SmallestNumber 
{
    public static void main(String[] args) 
    {
        int a,b,c;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the first number:");
        a = sc.nextInt();
        System.out.println("Enter the second number:");
        b = sc.nextInt();
        System.out.println("Enter the third number:");
        c = sc.nextInt();
        if(a < b && a < c)
        {
            System.out.println("The smallest number is:"+a);
        }
        else if(b < c)
        {
            System.out.println("The smallest number is:"+b);
        }
        else
        {
            System.out.println(" The smallest number is:"+c);
        }
 
    }
}
                                      

输出

Enter the first number:100
Enter the second number:105
Enter the third number:1
The smallest number is:1