Shawn
Shawn

Reputation: 307

Taking average of user input number

This is my code

import java.util.*;
import java.io.*;

public class eCheck10A
{
public static void main(String[] args)
{
  PrintStream out = System.out;
  Scanner in = new Scanner(System.in);

  out.print("Enter your integers");
  out.println("Negative = sentinel");

  List<Integer> aList = new ArrayList<Integer>();



  for (int n1 = in.nextInt(); n1 > 0; n1 = in.nextInt())
  {
          if(n1 < 0)
          {
          break;
          }
  }


 }
}

if i want to take all the numbers that I enter for n1, and average them out, how do i refer to all these numbers? I am going to put them in the IF statement, so if a negative number is entered, the program stops and posts their average.

Upvotes: 0

Views: 2584

Answers (3)

DTecMeister
DTecMeister

Reputation: 76

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.

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881263

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.

Upvotes: 2

jpniederer
jpniederer

Reputation: 140

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.

Upvotes: 0

Related Questions