如何根据用户输入查找最小数-Java

如何根据用户输入查找最小数-Java,java,Java,我试图从用户的输入(5个输入)中找到最小的数字。但是,每次我单击run并记下数字时,最小的数字总是“0”。这是我的密码: import java.util.Scanner; 公开课Q2_9{ 公共静态void main(字符串[]args){ //TODO自动生成的方法存根 int计数器=1; 双数; 双最小=0; 扫描仪s=新的扫描仪(System.in); while(计数器数字){ 最小=数量; } 计数器++; } System.out.println(“最小的数字是”+最小的); s、

我试图从用户的输入(5个输入)中找到最小的数字。但是,每次我单击run并记下数字时,最小的数字总是“0”。这是我的密码:

import java.util.Scanner;
公开课Q2_9{
公共静态void main(字符串[]args){
//TODO自动生成的方法存根
int计数器=1;
双数;
双最小=0;
扫描仪s=新的扫描仪(System.in);
while(计数器<6){
System.out.println(“输入编号:”);
数字=s.nextDouble();
如果(最小值>数字){
最小=数量;
}
计数器++;
}
System.out.println(“最小的数字是”+最小的);
s、 close();
}
}
算法:

  • 输入第一个数字,并假设它是最小的数字
  • 输入其余的数字,在此过程中,如果输入的数字小于该数字,则替换最小的数字
  • 演示:

    import java.util.Scanner;
    
    public class Main {
    
        public static void main(String[] args) {
            final int LIMIT = 5;
            int counter = 1;
            double number;
    
            Scanner s = new Scanner(System.in);
    
            // Input the first number
            System.out.print("Enter the number: ");
            number = s.nextDouble();
            double smallest = number;
    
            // Input the rest of the numbers
            while (counter <= LIMIT - 1) {
                System.out.print("Enter the number: ");
                number = s.nextDouble();
    
                if (smallest > number) {
                    smallest = number;
                }
    
                counter++;
    
            }
    
            System.out.println("The smallest number is " + smallest);
        }
    }
    
    Enter the number: -4040404
    Enter the number: 808080
    Enter the number: -8080808
    Enter the number: 8989898
    Enter the number: -8989898
    The smallest number is -8989898.0
    

    注意:不要关闭
    扫描仪(System.in)
    ,因为它也会关闭
    系统。在
    中,无法再次打开它。

    在更新
    最小的
    之前测试
    是否(最小的>数字)
    ,但将其初始化为0,因此,除非用户输入负数
    最小值
    将始终为0。一个解决方案是将其初始化为
    Integer.MAX\u VALUE
    而不是0,这样第一个输入将始终被视为低于您初始化的
    minimable
    值!所以我看到的是,我把最小的数字记为0,所以如果用户的输入值低于0,它就会打印出来。我真的不明白为什么你必须把Integer.MAX\u值。我刚开始使用Java,这很难:/@scotthouton:如果用户的输入值低于0,它会打印出来!问:您输入了哪5个数字(最小的还是“0”)?注:“for循环”是一个有用的成语。示例:
    for(int counter=0;counter<5;counter++){…}
    @palsm4非常感谢!你们帮了我大忙:“)@ArvindKumarAvinash噢,多谢了!我对StackOverflow很陌生他在整个程序结束后关闭了扫描仪,这意味着他不想让扫描仪接收其他输入,这节省了我们的资源leak@SwapnilPadaya-在
    系统的情况下,
    中可能存在可忽略的资源泄漏。但是,关闭
    扫描仪(System.in)
    的风险在于无法再次打开它。因此,如果您的应用程序只有一个程序,这将不会是一个问题,但是如果您的应用程序有其他程序,并且其中任何一个程序需要从键盘获取输入,您将得到一个异常。检查。你可以在上面找到更多这样的讨论。是的,对于一个程序来说没有任何问题,但是对于一个有其他程序的应用程序来说,可能会导致异常。