Java Reference
In-Depth Information
Display 3.8
Averaging a List of Scores
1
import
java.util.Scanner;
2
public
class
Averager
3{
4
public
static
void
main(String[] args)
5
{
6
Scanner keyboard =
new
Scanner(System.in);
7
System.out.println("Enter a list of nonnegative scores.");
8
System.out.println("Mark the end with a negative number.");
9
System.out.println("I will compute their average.");
10
double
next, sum = 0;
11
int
count = 0;
12
next = keyboard.nextDouble( );
13
while
(next >= 0)
14
{
15
sum = sum + next;
16
count++;
17
next = keyboard.nextDouble( );
18
}
19
if
(count == 0)
20
System.out.println("No scores entered.");
21
else
22
{
23
double
average = sum/count;
24
System.out.println(count + " scores read.");
25
System.out.println("The average is " + average);
26
}
27
}
28
}
Sample Dialogue
Enter a list of nonnegative scores.
Mark the end with a negative number.
I will compute their average.
87.5 0 89 99.9 -1
4 scores read.
The average is 69.1.