Nikhil Meshram
Nikhil Meshram

Reputation: 11

Smallest and Second Smallest of a number list

Problem 2 Write your program in the file TwoSmall.java.

Input a set of positive integers, ending with -1 as a sentinel. Print the smallest and second smallest of these numbers in that order.

You may assume there are always at least two numbers before the -1; you do NOT have to check for this being true.

public class TwoSmall{

    public static void main(String [] args){
        int min;
        int secondMin;
        int sentinel = -1;

        System.out.println("Enter atleast two numbers");    
        int input = IO.readInt();

        min = input;
        secondMin = input;

        do{

                if(input < min){
                    secondMin = min; 
                    min = input;
                }

                else if (input < secondMin) {
                    secondMin = input; 
                }
                input = IO.readInt();
            } while(input!=sentinel);

            System.out.println(min);
            System.out.println(secondMin);
    }

}

This is not working? Could someone tell me what is wrong with this program?

Upvotes: 1

Views: 3226

Answers (1)

Clint
Clint

Reputation: 930

It's because you set both min and secondMin equal to the first entered value. Unless the numbers entered are less than that value, you'll have an issue. Try reading in both those numbers separately.

min = IO.readInt();
secondMin = IO.readInt();

Also, rethink your logic. You might be getting a backwards result. A way to work yourself around this problem is to read the first two integers, then assign them to min and secondMin accordingly. Otherwise, if the user enters 4,3,2 -- the result will say that 3 is the lowest and that 2 is the second lowest - which is incorrect.

Another option, as mentioned by @vandale is to initialize both of them to INTEGER.MAX_VALUE. If you do this, you eliminate the need to read in initial values for min and secondMin.

Upvotes: 2

Related Questions