0

What is the error in this program?To display even numbers in arraylist?

import java.util.Scanner; import java.util.ArrayList; import java.util.Arrays; public class Program { public static void main(String[] args) { Scanner s=new Scanner (System .in); int n=s.nextInt(); int [] a=new int [n]; ArrayList<Integer> evenlist=new ArrayList<Integer>(); for(int i=0;i<a.length;i++) { a[i]=s.nextInt(); if(a[i]%2==0) { evenlist.add(a[i]); } } for(int i:evenlist) { System.out.println(i); } } }

8th Aug 2023, 2:16 PM
KGS Sumanth
KGS Sumanth - avatar
9 Respostas
+ 3
import java.util.Scanner; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Program { public static void main(String[] args) { Scanner s=new Scanner (System .in); int n = s.nextInt(); //int [] a=new int [n]; List<Integer> evenlist = new ArrayList<Integer>(); for(int i = 0; i < n; i++) { int a = s.nextInt(); if(a % 2 == 0) evenlist.add(a); } for(int i : evenlist) System.out.println(i); } } Take input like: 5 1 2 3 4 5
8th Aug 2023, 3:31 PM
A͢J
A͢J - avatar
+ 1
The code you've provided seems correct for the most part. However, there is one issue in your code: you are not populating the array `a` with input values from the user before checking for even numbers. To fix this issue, you need to change this line: ```java int [] a=new int [n]; ``` to: ```java int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = s.nextInt(); } ``` Here's the updated code with the correction: ```java import java.util.Scanner; import java.util.ArrayList; import java.util.Arrays; public class Program { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int[] a = new int[n]; ArrayList<Integer> evenlist = new ArrayList<Integer>(); for (int i = 0; i < a.length; i++) { a[i] = s.nextInt(); if (a[i] % 2 == 0) { evenlist.add(a[i]); } } for (int i : evenlist) { System.out.println(i); } }
9th Aug 2023, 5:11 AM
‎ ຸ
+ 1
} With this change, your program should now correctly read input values into the array a and display even numbers in the evenlist ArrayList.
9th Aug 2023, 5:11 AM
‎ ຸ
0
There's some redundant code, but it works for me. What is the problem in your mind?
8th Aug 2023, 2:23 PM
Marcos Chamosa Rodríguez
Marcos Chamosa Rodríguez - avatar
0
It doesn't display anything
8th Aug 2023, 2:30 PM
KGS Sumanth
KGS Sumanth - avatar
0
It does for me. You're making a mistake somewhere else.
8th Aug 2023, 2:34 PM
Marcos Chamosa Rodríguez
Marcos Chamosa Rodríguez - avatar
0
Pls send code
8th Aug 2023, 2:37 PM
KGS Sumanth
KGS Sumanth - avatar
0
Is this code correct
8th Aug 2023, 2:38 PM
KGS Sumanth
KGS Sumanth - avatar
0
I did not change the code. Your code works. As a side note though, if you only want to print a list of numbers, you don't need both a list and an array. Use only one.
8th Aug 2023, 2:39 PM
Marcos Chamosa Rodríguez
Marcos Chamosa Rodríguez - avatar