user2984143
user2984143

Reputation: 85

Calculating the average in a Loop Java

I just found that when I calculate the average for the second user, I get a different result. For example, if I add this number for the first user 10,10,10,20,20. I get 14.0 which is correct. But when I enter the same number for the second user I get 28.0? any ideas?

import java.util.Scanner;

public class midterm 
{
  public static void main(String args[]) 
  {
    Scanner kb = new Scanner(System.in);

    int max = Integer.MIN_VALUE;
    int min = Integer.MAX_VALUE;
    int sum = 0;
    double average=0;
    int count = 0;
    int salary_annually = 0;

    for(int employee =1; employee <= 2; employee++)
    {
      System.out.println("Employee: " + employee);

      for(int year=1; year <= 5; year++)
      {   
        System.out.println("Please Enter the Salary for Year: "  + year);
        salary_annually = kb.nextInt();

        sum += salary_annually  ;
        average = (sum) / 5.0; 

        if (min >= salary_annually) 
        { 
          min = salary_annually;
        } 

        if (max <=salary_annually) 
        { 
          max = salary_annually;
        } 
      }

      System.out.println("The average is " + average);
      System.out.println("The higher number  " + max);
      System.out.println("The the lowest number " + min);
    }
  }
}

Upvotes: 1

Views: 117

Answers (2)

hasan
hasan

Reputation: 24205

sum = 0; // this before 2nd loop
int max = Integer.MIN_VALUE; // these too.
int min = Integer.MAX_VALUE;
for(int year=1; year <= 5; year++)
{
   .
   .
   .
}
average = (sum) / 5.0; // this after 2nd loop

In your solution you are calculating average 5 times inside the loop! and you only get advantage from the fifth time! must be after the loop. average = (sum) / 5.0; after the loop.

Upvotes: 2

t0mppa
t0mppa

Reputation: 4078

You need to zero sum at the end of the loop. As it is, now it just keeps increasing and increasing as the old value is kept in memory, when coming to the next iteration.

Upvotes: 1

Related Questions