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

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<Integer> value = new ArrayList<Integer>();
        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#
Aominè Reply to 2017-12-07 21:55:26Z

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.

Nattydredd
3#
Nattydredd Reply to 2017-12-07 21:54:15Z

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<Integer> value = new ArrayList<Integer>();
    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);
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.349248 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO