java code, finding the min, max and average of floating point numbers -


i wrote below code works fine except never executes last loop last value inputted never calculated min/max/average. idea went wrong?

import java.util.scanner; public class program4_johnhuber {  public static void main(string[] args) {     scanner input = new scanner (system.in);     double total = 0;    //double numbers = 0;    int count = 1;    double largest = 0;    double smallest = double.max_value;    double average = 0;     system.out.print ("please enter grades, (press enter when finished): ");    {        while (input.hasnextdouble()&& count<5)        {            double entered = input.nextdouble();            total = total + entered;            //count++;         //double average = 0;        if (count > 0)        {            average = total/count;        }        if (entered > largest)        {            largest = entered;        }        if (entered < smallest)        {            smallest = entered;        }        count++;        }     }        system.out.printf ("your average grade %3.2f,\n", average);        system.out.printf ("your highest grade %3.2f \n", largest);        system.out.printf ("your lowest grade %3.2f \n", smallest);    } } 

there 2 errors in program (assuming intent input 5 numbers):

  1. you're using count indicate number of grades you've entered already. before you've entered grades, how many grades have entered? that's value count should have, you've initialized wrong value.
  2. the other issue in how you've written while:

       while (input.hasnextdouble() && count<5) 

suppose you've fixed first problem, lets enter 5 numbers , keeps statistics on numbers. goes while loop , evaluates boolean expression.

at point, count 5, want exit loop. doesn't happen, because input.hasnextdouble() evaluated first. since you're using scanner on system.in, means program waits until either type in isn't blank, or until indicate end of input ctrl+d on linux or ctrl+z on windows. after finds next item in input, exit loop if can't find double (e.g. type in letters); or if put in double, then checks count.

the combination of these 2 errors why program appears ignoring last input: (1) computation on 4 grades, not 5, because of error in initializing count, , (2) asks 5th grade anyway, because parts of while loop condition in wrong order.

to fix second problem, change to

while (count < 5 && input.hasnextdouble()) 

this checks count first, , exits loop when have enough grades, instead of looking more input.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -