This is my code
import java.util.*;
import java.io.*;
public class eCheck10A
{
public static void main(String[] args)
{
PrintStream out = System.out;
Scanne
An outline of what you will need to do: Create a variable sum to add up all of the values and create another variable called count that will be used to store the number of non-negative numbers in your list, aList. Then divide the sum by the count to find the average.
This is the pseudocode you need to do this task (pseudo-code since it looks suspiciously like homework/classwork and you'll become a better developer if you nut out the implementation yourself).
Because you don't need the numbers themselves to work out the average, there's no point in storing them. The average is defined as the sum of all numbers divided by their count, so that's all you need to remember. Something like this should suffice:
total = 0
count = 0
n1 = get_next_number()
while n1 >= 0:
total = total + n1
count = count + 1
n1 = get_next_number()
if count == 0:
print "No numbers were entered.
else:
print "Average is ", (total / count)
A couple of other points I'll mention. As it stands now, your for
statement will exit at the first non-positive number (<= 0
), making the if
superfluous.
In addition, you probably want any zeros to be included in the average: the average of {1,2,3} = 2
is not the same as the average of {1,2,3,0,0,0} = 1
.
You can do this in the for
statement itself with something like:
for (int n1 = in.nextInt(); n1 >= 0; n1 = in.nextInt())
and then you don't need the if/break
bit inside the loop at all, similar to my provided pseudo-code.
Another way to do running average is:
new_average = old_average + (new_number - old_average ) / count
If you ever hit max for a variable type, you would appreciate this formula.