ArrayList | Sololearn: Learn to code for FREE!

+3

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 } }

5/16/2021 9:13:10 AM

Swapnil Kamdi

1 Answer

New Answer

+5

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());