Home I want to average the numbers inputted into the ArrayList, however it only calculates average as 0.0

# I want to average the numbers inputted into the ArrayList, however it only calculates average as 0.0

J. Green
1#
J. Green Published in 2017-12-07 21:36:08Z
 It sums perfectly fine, however it averages the values as 0.0 no matter what numbers I input. How can I make it output the correct average value? import java.util.Scanner; import java.io.*; import java.util.ArrayList; public class Calculation { static Toolkit tools = new Toolkit(); public static void main(String [] args) { double average = 0.0; double sum = 0; int i =0; int num = 0; int nElements = 0; Scanner console = new Scanner(System.in); ArrayList value = new ArrayList(); System.out.println("Enter value: "); num = console.nextInt(); while(num != 0) { value.add(new Integer(num)); } for(i = 0; i < value.size(); i++) { sum += value.size(); } average = sum / value.size(); System.out.println("Number of values read: " + value.size()); System.out.println("Values sum: " + sum + "Values average: " + average); System.exit(0); } } 
Aominè
2#
 as is now, the loop will only end if you enter 0 the first time otherwise it will lead to an infinite loop. rather, you'll need to read the next integer within the loop as such: while(num != 0) { value.add(new Integer(num)); num = console.nextInt(); // add this line }  Also, change this: sum += value.size();  to this: sum += value.get(i);  as you'll want to reduce the numbers inside the ArrayList into a single value rather than performing the summation of the ArrayList's size on each iteration.
 What Aomine said is correct. However, it is not the only problem. Inside your for loop you are adding the size of your Arraylist to your 'sum' variable. You should be adding the values it holds instead, i.e. summing them. double average = 0.0; double sum = 0; int i = 0; int num = 0; Scanner console = new Scanner(System.in); ArrayList value = new ArrayList(); System.out.println("Enter value: "); num = console.nextInt(); while (num != 0) { value.add(new Integer(num)); num = console.nextInt(); } for (i = 0; i < value.size(); i++) { sum += value.get(i); } average = sum / value.size(); System.out.println("Number of values read: " + value.size()); System.out.println("Values sum: " + sum + "Values average: " + average);