java - Trying to calculate the average in an ArrayList -
i'm trying write code takes in number of entries , stores in arraylist
given specific condition. i'm not able find average of values stored in arraylist
. here's code written 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: "); { t = input.nextint(); if (t == -99) { system.out.println("program terminating.."); break; } else { temp.add(t); } } while (t != -99); (int = 0; < temp.size(); i++) { if (temp.get(i) > 40) { count++; } } system.out.println(count); } }
you have funky condition there; you're doing operations if value greater 40. code below takes account; if don't desire that, remove conditional.
in traditional manner, can use enhanced-for counter of values greater 40 , average those...
double sum = 0; for(integer : temp) { if(i > 40) { sum += i; count++; } } if(count != 0) { // avoid divide-by-zero error here system.out.println(sum / count); }
...or java 8, can use streams, filter out less 40, , average double instead:
system.out.println(temp.stream() .filter(x -> x > 40) .maptoint(integer::intvalue) .average() .getasdouble());
Comments
Post a Comment