Got a quick question if anyone can help. I got an assignment for this problem:
Give a Java loop statement that will read in a list of numbers of type double and then output their average. The numbers are all greater than or equal to 1.0. The list is ended with a sentinel value. Please specify the sentinel value and give any declarations or initializing statements that are needed.
Here's the code I have for this so far:
import java.util.Scanner;
public class number1
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
double num, avg, next, sum, count;
avg = 0;
sum = 0;
count = 0;
System.out.println("Enter numbers.");
num = scan.nextDouble();
count++;
next = scan.nextDouble();
while(next > -1.0)
{
next = scan.nextDouble();
count++;
sum = num + next;
avg = sum / count;
System.out.println(avg);
}
}
}
The sentinel value is -1. I have the averaging working, except when i try to average more than 2 numbers, I get the wrong average printed out. Can someone help me figure this out?