javaarraysloopsarraylist

Remove multiple numbers from an ArrayList


I've got this exercise:

Write a program that constructs an ArrayList containing the numbers 1 to 100 and prints them out. Then ask the user for a number, and remove all multiples of that number (except for the number itself) from the list, and print the list out again. For example, if the user selects 5, it will remove 10, 15, 20, 25, 30, etc from the list.

And I can't seem to be done with the second part (removing all multiples)

So far this is what I've got:

package ArrayList1To100;

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

public class OneToHundreed {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ArrayList<Integer> list = new ArrayList<>();

        for (int i = 1; i <= 100; i++) {
            list.add(i);
        }
        System.out.println(list);
        System.out.println("Next part of the exercise\n_________________________");
        System.out.println("Please enter a number");
        final int input = sc.nextInt();

        int i = 2;
        int x = i * input;
        while (list.contains(x)) {
            list.remove(x - 1);
        }
        System.out.println(list);

    }
}

I get that my remove part is flawed as it only removes a single number. I've tried with an if statement, and a while. But I can't seem to find the connection.


Solution

  • You can use modulo operation.

    Code:

    System.out.println(list);
    System.out.println("Next part of the exercise\n_________________________");
    System.out.println("Please enter a number");
    final int input = sc.nextInt();
    // The result array that will contain correct numbers.
    ArrayList<Integer> result = new ArrayList<>();
    // For loop roams the initial dataset starting from first index.
    for (int i = 0; i < list.size(); i++) {
        // If the element in the initial array list is equal to
        // the input number, it will directly added to the result
        // array list.
        if (list.get(i) == input) {
            result.add(list.get(i));
        }
        // Otherwise, the modulo operation will be executed.
        // If the result of the modulo is greater than 0,
        // the number will be added to the result array list.
        else if ((list.get(i) % input) > 0) {
            result.add(list.get(i));
        }
    }
    System.out.println(result);