I'm new to Java and just need a little help....The program is supposed to have the user enter in a series of numbers then displays the largest and the smallest....they have to enter -99 to end. My problem is the smallest number is always -99.
What do i have wrong? Please help

import java.util.Scanner; // Needed for the scanner class

/** this program asks the user to enter numbers then displays the
largest and smallest numbers
*/

public class LargestAndSmallest
{
    public static void main(String [] args)
    {
    int number;  // user number
    int largeNumber = 0;
    int smallNumber = 0;

    // Create a Scanner object for keyboard input.
    Scanner keyboard = new Scanner(System.in);

    //Display general instructions
    System.out.println("Enter multiple numbers and this");
    System.out.println("program will tell you the largest");
    System.out.println("and the smallest number you inputed.");
    System.out.println("When you are done enter -99 to stop.");
    System.out.println();

    // have user enter in their first number
    System.out.print("Enter in number or -99 to end: ");
    number = keyboard.nextInt();

    while (number != -99)
    {
        // get the next number
        System.out.print("Enter in number or -99 to end: ");
        number = keyboard.nextInt();    

    if (smallNumber == 0 && largeNumber == 0)
        {
        smallNumber = number;
        largeNumber = number;
        }
    if (number < smallNumber)
        {
        smallNumber = number;
        }
    else if(number > largeNumber)
        {
        largeNumber = number;
        }
    }

     // Display the largest and the smallest number
     System.out.println();
     System.out.println("Your largest number is: " + largeNumber);
     System.out.println("Your smallest number is: " + smallNumber);

    }
}

Edited 3 Years Ago by mike_2000_17: Fixed formatting

You have two problems here.

  • The one in your code: You are not deciding to leave the loop until too late. Fix: Right before this line: if (smallNumber == 0 && largeNumber == 0) put this line: if(-99 == number) {break;}
  • The one in your posting: You should wrap your code in your code goes here tags. The easiest way is to use the (CODE) button on the menu bar. The result is good three ways: Your code is displayed

    • indented
    • with line numbers
    • with keyword coloring
  • Which is all good.

(don't forget to mark the thread "solved" if it is: Only you: the original poster, have the "Mark thread solved" link at the bottom of the screen)

Edited 3 Years Ago by mike_2000_17: Fixed formatting

This question has already been answered. Start a new discussion instead.