简体   繁体   中英

Java: Two Smallest numbers helo

So my code works in all test cases except for when there are only two integers. Example if user inputs: terminating number as -1 and then inputs 1,2 and then -1 again the smallest numbers are 1,1 and not 1,2

Terminating number is just the way to end the sequence/program.

public static void main(String[] args) {
        double num;
        double min = 0;
        double min2 = 0;

        System.out.println("Enter terminating value:");
        int term = IO.readInt();

        System.out.println("Enter next value:");
        num = IO.readDouble();

        if(num == term){
            IO.reportBadInput();
            main(args);
        }

        int count = 0;
        min = num;
        min2 = num;

        do{
            num = IO.readDouble();

            if(num!= term && num < min) {
                min2 = min;
                min = num;
            }
            else if (num!= term && num < min2) {
                min2 = num;
            }
            count++;
        }while (num != term);

        if(count < 2){
            IO.reportBadInput();
            main(args);
        }

        else{
        IO.outputDoubleAnswer(min);
        IO.outputDoubleAnswer(min2);
        }

    }

The issue with your code lies in setting both minimal values to the number that was first entered. This is bad because if the user enters the smallest value first, both min and min2 already contain the minimum value. That means the condition input < min2 is always false , causing min2 to always contain the value the user has entered first.

To fix this, simply set the value of min2 to a value which is larger than any other value the user could enter (for example Double.MAX_VALUE or Double.POSITIVE_INFINITY ).

Just as a hint concerning the error-handling part of your code: if you call main again after reminding the user that their input was invalid, make sure to add a return behind that call or the execution will continue after the called main method is finished. Something like this:

if (count < 2) {
    IO.reportBadInput();
    main(args);
    return;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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