Java bootcamp · Lab 34

Keep the evens

easyArrayList10 minLesson: ArrayList

Read the question, write Java on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read n then n ints; print evens space-separated.

Examples

Example 1
Input
5
1 2 3 4 5
Output
2 4
Hint
  1. Collect evens then join with spaces.
Show correct code

Peek only after you have tried. You can still Check your own version.

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    ArrayList<Integer> out = new ArrayList<>();
    for (int i = 0; i < n; i++) {
      int x = in.nextInt();
      if (x % 2 == 0) out.add(x);
    }
    for (int i = 0; i < out.size(); i++) {
      if (i > 0) System.out.print(' ');
      System.out.print(out.get(i));
    }
    System.out.println();
  }
}
Main.javaJava 21 · javac · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.