Results 1 to 3 of 3
  1. #1
    trofyscarz is offline Member
    Join Date
    Oct 2008
    Rep Power

    Default printing two smallest numbers from a series of numbers

    Instructions: Write and debug a program by implementing a class called twoSmallest, which prompts the user to enter a series of numbers. Each number can have a fractional part. The user indicates the end of the list by typing a “z” as the next number. The program then prints out the two smallest numbers among the list that the user typed. The result for this problem should be a Java file called

    I am having no problem exiting the loop and printing the smallest number, I just cant figure out how to print the second smallest number.
    Any suggestions?

    import java.util.Scanner; // Needed for the Scanner class
    public class TwoSmallest

    public static void main(String[] args)

    double smallest = Double.MAX_VALUE;
    double secondsmallest ;

    // Create a Scanner object for keyboard input.

    Scanner sc = new Scanner(;

    // Display general instructions.

    System.out.println("Enter a series of numbers.");

    System.out.println("Press Z to exit the program.\n");

    boolean exit = false;

    while (!exit)


    System.out.print("Enter a value ");

    String input =;

    if (input.equalsIgnoreCase("Z"))

    exit = true;



    double x = Double.parseDouble(input);

    smallest = Math.min(smallest ,x);


    System.out.println("Smallest number: " + smallest);



  2. #2
    emceenugget is offline Senior Member
    Join Date
    Sep 2008
    Rep Power


    Two quick solutions I could think of.

    1. You can take the easy route by inserting all inputs into a list, sorting it, and taking the first two values.

    2. Obviously, you can keep track of two numbers instead of one in your loop. It only takes a little bit of thinking on how you would update those variables as you get each input.

  3. #3
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Eastern Florida
    Rep Power


    I just cant figure out how to print the second smallest number.
    This should do it:
    System.out.println("Second smallest= " + secondsmallest);

Similar Threads

  1. Counting numbers up and down
    By radio in forum New To Java
    Replies: 4
    Last Post: 05-06-2011, 03:03 PM
  2. Random numbers
    By jithan in forum Advanced Java
    Replies: 3
    Last Post: 06-14-2008, 02:04 PM
  3. Prime numbers
    By tercius in forum New To Java
    Replies: 3
    Last Post: 05-04-2008, 06:05 AM
  4. Compare 5 numbers
    By Snowboardmylife in forum New To Java
    Replies: 5
    Last Post: 04-15-2008, 07:04 PM
  5. Printing Fibonacci Numbers
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-09-2008, 06:43 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts