Java | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Java

ArrayList PRACTICE EXERCISE ArrayList The program you are given declares an even nums ArrayList. Write a program to take numbers as input and add them an ArrayList while the size of the ArrayList isn't equal to 3. Then calculate and output the average of all values in integers. Sample Input 5 2 4 Sample Output 3 Use evennums.size() in while loop condition. Stuck? This is my 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 if(num % 2 ==0) { evenNums.add(num); } } double average=calculateAverage(evenNums); //calculate and output the average integer value System.out.println("The average of the even number is"+average); } public static double calculateAverage(ArrayList<Integer> numbers){ double sum=0; for(int number: numbers){ sum+=number; } return sum/numbers.size(); } } The error is due to no input provided for the scanner resulting in a `NoSuchElementException` when trying to read an integer input.

25th May 2024, 5:53 AM
Div Anand
Div Anand - avatar
1 Answer
+ 2
I believe the problem is with how you're adding numbers to the array. You check with modulus 2, but you don't need to. The requirements don't state to only accept odd numbers, so your code is forever waiting on more inputs. Also, you shouldn't use double as the answer is "the average of all values in *integers*"
25th May 2024, 8:13 AM
Ausgrindtube
Ausgrindtube - avatar