开发者

Find two smallest numbers using java?

I need help to compute the two smallest numbers in java?... plzz help.. Usage for arraylist and arrays are not allowed.. The user shall be 开发者_开发知识库asked for a terminating value first and will continue to provide inputs and once the user enters the same terminating value the program should output the two smallest numbers from the inputs excluding the terminating value..

Additional Details Could show me how to do it... The sentinel value is the value if entered again by the user shall stop the program and output the two smallest numbers.

package hw4;


public class s1 {

    public static void main(String[] args) {

        int input;
        int min;
        int min2;



        System.out.print("Enter a value to act as sentinel:");
        int sentinel = IO.readInt();

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

        do {

            min = input;
            min2 = input;

            if (input < min) {

                min = input;

            }



            input = IO.readInt();

        } while (input != sentinel);

        // Return the results
        System.out.println("The smallest Number is: " + min);
        System.out.println("The second smallest Number is: " + min2);
    }
}


I'm assuming this is homework, based on the nature of the question. So ...

Hint: if x was the smallest and y is now the smallest, then x is now the second smallest.

Hint 2: make sure your program works when the smallest and second smallest values are equal.


When you find a new min, save the previous minimum in your min2 variable and then reassign min to the current input.

   if (input < min) {
        min2 = min
        min = input;

    }


This would work if you needed to find only the smallest number, but you need to find the two smallest numbers, so the if should go like that:

if(input < min) {
    min2 = min;
    min = input;
}
else if (input < min2) {
    min2 = input;
}

And I know min & min2 need a value at start, so instead of changing their value to input every time, just do that at the fist time. So also get this part out of the do:

min = input;
min2 = input;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜