+ 4

ArrayList

I'm not getting the desired output in below code. It comes as looping. Please help to correct the code. import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[ ] args) { Scanner scanner = new Scanner(System.in); ArrayList<Integer> evennums = new ArrayList<Integer>(); while(evennums.size()<3){ int num = scanner.nextInt(); //your code goes here evennums.add(num); int sum = 0; for (int i: evennums) sum += i; int b = evennums.size(); System.out.println(sum/b); } //calculate and output the average integer value } }

16th May 2021, 9:13 AM
Swapnil Kamdi
Swapnil Kamdi - avatar
1 Answer
+ 6
It comes as looping because the calculation of average is inside the while loop. while(evennums.size()<3){ int num = scanner.nextInt(); //your code goes here evennums.add(num); }//close while //calculate and output the average integer value int sum = 0; for (int i: evennums){ sum += i; }//close for loop //print average System.out.println(sum/evennums.size());
16th May 2021, 10:12 AM
Denise Roßberg
Denise Roßberg - avatar