+ 1

I can't understand the this error

import java.util.ArrayList; import java.util.*; import java.io.*; public class Main { public static void main(String[ ] args) { Scanner scanner = new Scanner(System.in); int tot=0;int avg=0; ArrayList<Integer> evennums = new ArrayList<Integer>(3); while(evennums.size()<3){ int num = scanner.nextInt(); //your code goes here tot = tot+num; } avg=tot/3; System.out.println(avg); //calculate and output the average integer value } }

19th Aug 2022, 12:45 PM
Amala Yakin
5 odpowiedzi
+ 1
Your while loop is infinite loop. Where is you using ArrayList in your program? You just initialized, never updating it so its size remiains 0 forever.. Instead add input to list or use a counter variable instead of list.size()... hope it helps....
19th Aug 2022, 12:59 PM
Jayakrishna 🇮🇳
+ 1
But i used the arraylist named as evennums... And how to you know it's infinite loop
19th Aug 2022, 1:13 PM
Amala Yakin
+ 1
You are posted same code..! See ArrayList<Integer> evennums = new ArrayList<Integer>(3); //you declared arraylist here, initially size is 0. No elements added yet. while(evennums.size()<3){ // here it is condition now is while( 0< 3){ // true ... In loop here, you never adding to list so size still remains zero. } So next iteration, 0<3 true . . This loop never stops since condition 0<3; Instead add to list by evennums.add(num); in loop Else, no need list. Take counter int count = 0; while( count < 3 ){ int num = scanner.nextInt(); tot += num; count++; }
19th Aug 2022, 3:01 PM
Jayakrishna 🇮🇳
0
while( evennums.size() < 3 ) { What is size() each time returns in loop? It's always zero.. Where are you using list?
19th Aug 2022, 2:16 PM
Jayakrishna 🇮🇳
0
This one correct or not import java.util.ArrayList; import java.util.*; import java.io.*; public class Main { public static void main(String[ ] args) { Scanner scanner = new Scanner(System.in); int tot=0;int avg=0; ArrayList<Integer> evennums = new ArrayList<Integer>(3); while(evennums.size()<3){ int num = scanner.nextInt(); //your code goes here tot = tot+num; } avg=tot/3; System.out.println(avg); //calculate and output the average integer value } }
19th Aug 2022, 2:41 PM
Amala Yakin