简体   繁体   English

如何在此Java程序中获取逻辑以使循环正常工作?

[英]How do I get my logic in this Java program to make my loop work?

I've made this java program to find the two smallest integers as inputted by the user. 我制作了这个Java程序来查找用户输入的两个最小整数。 I think I'm pretty much just about there except there is one issue with my logic. 我认为我几乎就在那里,除了我的逻辑存在一个问题。 I'm not sure what to set values: 我不确定要设置什么值:

   int min, min2;

to where the rest of my program would work. 到我的程序其余部分可以工作的地方。 I've tried -1 and 0 and it will just come out at the end as both my smallest and second smallest. 我尝试过-1和0,它会以我的最小和第二个最小数出现在最后。

public class TwoSmall
{
    public static void main(String[] args)
    {
    int input;

    System.out.println("Enter you numbers: ");
    input = IO.readInt();
    int min = 0;
    int min2 = 0;

    while (input >= 0)
    {
        if (input < min)
        {
            min2 = min;
            min = input;
        }
        else if (input < min2)
        {
            min2 = input;
        }
        input = IO.readInt();
    }

    System.out.println("The lowest number was " + min 
                         + " and the second lowest is " + min2);



    }
}

Try setting min and min2 to Integer.MAX_VALUE . 尝试将minmin2设置为Integer.MAX_VALUE Practically this should solve your problem because the data type of integers you are working with is int . 实际上,这应该可以解决您的问题,因为要使用的整数的数据类型为int But theoretically, setting min and min2 to the first input value is the correct solution. 但是从理论上讲,将minmin2设置为第一个输入值是正确的解决方案。

EDIT: As a matter of fact, I see that you input the first value separately. 编辑:事实上,我看到您分别输入了第一个值。 Hence the correct solution is as below: 因此,正确的解决方案如下:

public class TwoSmall
{
    public static void main(String[] args)
    {
        int input;

        System.out.println("Enter you numbers: ");
        input = IO.readInt();
        int min = input;
        int min2 = input;

        while (input >= 0)
        {
            numInputsGreaterThan1 = true;
            if (input < min)
            {
                min2 = min;
                min = input;
            }
            else if (input < min2)
            {
                min2 = input;
            }
            input = IO.readInt();
        }

        System.out.println("The lowest number was " + min 
                         + " and the second lowest is " + min2);
     }
}

Note that in case, only a single integer is input, the value of min and min2 printed will be the same. 注意,如果仅输入一个整数,则输出的minmin2的值将相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM