Reputation: 109
I have been learning Java for about a week and I was working on a program that finds the average of any amount of numbers. But I faced a problem where it would divide every number by the total number, instead of dividing the sum of all values. I also tried finding the last value of the Array list and then divide it by the count. But it didn't work.
This is my code :
import java.util.Scanner;
import java.util.*;
public class Average {
public static void main (String args[]){
double average, count, orig = (double) 0;
double all =(double) 0;
Scanner input = new Scanner (System.in);
ArrayList<Double> list = new ArrayList<Double>();
while (input.hasNextDouble()) list.add(input.nextDouble());
count = (double) list.size();
for (Double x: list) {
all += x;
average = all/count;
System.out.println(average);
double e = average.get(average.size() - 1);
System.out.println(e);
}
}
}
and the output is :
21
20
23
24
25
a
4.2
8.2
12.8
17.6
22.6
25.0
Upvotes: 1
Views: 953
Reputation:
You are keeping too much code in the loop. While you iterate over the list of doubles, you only need to keep a running total. Afterwards, you should then compute the average as the sum of doubles divided by the size of the list.
Here is how to fix the loop:
for (Double x: list)
{
all += x;
}
average = all/count;
System.out.println(average);
//These lines are not useful, so they are commented out.
//double e = average.get(average.size() - 1);
// System.out.println(e);
Upvotes: 0
Reputation: 463
There are quite a few redundancies with your code.
double average, count, orig = (double) 0;
can be written as:
double average, count, orig = 0.0d;
(you should consider checking float and decide which suits you better - doesn't really matter here)
Since java 1.7, you can declare lists in a shorter manner (search "diamond expression").
ArrayList<Double> list = new ArrayList<>();
In the line
double e = average.get(average.size() - 1);
you probably ment list
instead of average, which should fix the error in the title.
Right now your code is printing average multiple times and only the last time is the real average of list items. Consider moving printing command of average out of for loop.
try this:
for (Double x: list)
{
all += x;
}
average = all/count;
System.out.println(average);
Upvotes: 1
Reputation: 2229
You cannot call size() method on primitive data type.It can be called on java.util.List
,etc. So your double e = average.get(average.size() - 1);
makes no sense.
You can directly write:
average = all/count;
Upvotes: 1