Find average of numbers (with while loops; java)

My code stops when the user inputs -1 (like it should) but the average printed is wrong.

This is what I have:

import static java.lang.System.*;
import java.util.Scanner;
import java.util.*;

class averages_1
{
    public static void main(String[] args)   
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the scores:");
        double score = 0;
        double num = 0;
        double sum = 0;

    while (score != -1)
    {
        score = scan.nextDouble();
        sum += score;
        num++;
    }
    System.out.println("The average is:" + (sum/num));
}

}

If you enter 50 then 105 then -1, the output is

Enter the scores:

50

105

-1

The average is: 51.333333333333336

I just need to correct the average. Any help is appreciated!

Answer

You include the -1 in your average.

One way to avoid it is to add another condition :

while (score != -1)
{
    score = scan.nextDouble();
    if (score != -1) {
        sum += score;
        num++;
    }
}

However, a more elegant solution would read the first input before the loop, and only add valid inputs :

score = scan.nextDouble();
while (score != -1)
{
    sum += score;
    num++;
    score = scan.nextDouble();
}

In general, changing the variable used in the condition of the while loop should be the last thing you do in the iteration.

Leave a Reply

Your email address will not be published. Required fields are marked *