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); } } }
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
+ 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);
}
}
+ 1
}
With this change, your program should now correctly read input values into the array a and display even numbers in the evenlist ArrayList.
0
There's some redundant code, but it works for me. What is the problem in your mind?
0
It doesn't display anything
0
It does for me. You're making a mistake somewhere else.
0
Pls send code
0
Is this code correct
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.