Arvind Suryanarayana
Arvind Suryanarayana

Reputation: 247

Trying to calculate the average in an ArrayList

I'm trying to write some code which takes in any number of entries and stores it in an ArrayList given a specific condition. What I'm not able to do is find the average of the values stored in the ArrayList. Here's the code written so far:

import java.util.ArrayList;
import java.util.Scanner;

public class App {
    private ArrayList<Integer> temp;
    private int t;
    private int count = 0;

    public void main() {
        Scanner input = new Scanner(System.in);
        temp = new ArrayList<>();
        System.out.println("Enter temperatures: ");
        do {
            t = input.nextInt();
            if (t == -99) {
                System.out.println("Program Terminating..");
                break;
            } else {
                temp.add(t);
            }
        } while (t != -99);
        for (int i = 0; i < temp.size(); i++) {
            if (temp.get(i) > 40) {
                count++;
            }

        }
        System.out.println(count);

    }
}

Upvotes: 1

Views: 1466

Answers (2)

Makoto
Makoto

Reputation: 106420

You have a funky condition there; you're only doing operations if the value is greater than 40. The code below takes those into account; if you don't desire that, then remove the conditional.

In a traditional manner, you can use an enhanced-for with a counter to get all of the values greater than 40 and average those...

double sum = 0;
for(Integer i : temp) {
    if(i > 40) {
        sum += i;
        count++;
    }
}

if(count != 0) { // avoid divide-by-zero error here
    System.out.println(sum / count);
}

...or with Java 8, you can use streams, filter out those that are less than 40, and get the average as a double instead:

System.out.println(temp.stream()
                       .filter(x -> x > 40)
                       .mapToInt(Integer::intValue)
                       .average()
                       .getAsDouble());

Upvotes: 2

TheConsultant
TheConsultant

Reputation: 94

 long total =0;
  for(int i=0;i < temp.size(); i++){
    if(temp.get(i) > 40){
        count++;
        total+=temp.get(i);
    }
   }

    double mean=0;
   if(count!=0)
        mean = total/count;

Upvotes: 0

Related Questions