Search code examples
javawhile-loopmaxmin

How do I find the largest number and the smallest number from the user input? (while loop)


Not sure where to begin honestly, I was able to find average using the user's input but can't seem to figure out the largest number or the smallest number from the numbers entered. Is there a method I can use? Any help would be great. Thank you.

EDIT: Somewhat figured it out. However the answers always seem to be largest number = 2.1478... or Smallest number = -2.1478...

Scanner input = new Scanner(System.in);


System.out.println("Enter the number of grades: ");
double random = input.nextDouble();
double min = Integer.MIN_VALUE;
double max = Integer.MAX_VALUE;

double total=0;
int count = 1;
while (count < random+1) {




    System.out.println("Enter grade " + count + ":");

    double somenumber = input.nextDouble();
    total+=somenumber;

    count++;

    if (somenumber > max){
        max = somenumber;
    }
if (somenumber < min){
    min = somenumber;
}


}
System.out.println("Total is " + total);
System.out.println("Average is " + (total/random));
System.out.println("Largest number is " + max);
System.out.println("Smallest number is" + min);



        }

}


Solution

  • Above while loop...

    double max = 0;
    double min = Double.MIN_VALUE;
    

    In loop after you set some number...

    if (someNumber > max){
      max = someNumber;
    }
    if (someNumber < min){
      min = someNumber;
    }
    

    Np glad it helped :) you should consider using a for loop instead of a while loop and declare someNumber outside of the loop like so:

    double someNumber;
    for (int i = 1; i <= random; i++){
      //...
    }
    

    To make it even cleaner you could replace i <= random in the for loop with

    i <= readNumGrades(input);
    private double  readNumGrades(Scanner in){
      System.out.println("Enter the number of grades");
      return in.nextDouble();
    }
    

    So you no longer need the variables count and random