ArrayList and iterator Example 3

Code Explanation

LineDescription
6method header of the method addOrRemoveElements() with the input parameters selection of type char, reader of type Scanner and list of type ArrayList. It is a private, static method of type void, which means that no return value is expected.
10 – 38Expects input from the user until the user terminates it with an input (n).
40 – 46private, static method called printElements() expects an ArrayList as input parameter and prints all elements of the ArrayList.
49Creates a variable called reader of type Scanner
50Creates a ArrayList called cars of type String
52 – 54Adds the elements BMW, Mercedes and Ferrari to the ArrayList with the add() method
57 + 65Calls the method printElements() with the input parameter cars to print the elements of this ArrayList.
59 – 62Asks the user whether to add or delete elements from the ArrayList. Then the method addOrRemoveElements() is called, depending on the previously made input.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;

class ArrayListAddRemove {
	private static void addOrRemoveElements(char selection, Scanner reader, ArrayList list) {
		char c = 'y';
		String element;

		while (c == 'y') {
			switch (selection) {
			case 'a':
				System.out.print("Please enter element to add: ");
				element = reader.nextLine();
				list.add(element);

				System.out.print("continue adding? (y / n) ");
				c = reader.nextLine().charAt(0);
				break;
			case 'r':
				System.out.print("Please enter element to remove: ");
				element = reader.nextLine();

				if (list.contains(element)) {
					list.remove(element);
				} else {
					System.out.println("Element not found!");
				}

				System.out.print("continue removing? (y / n) ");
				c = reader.nextLine().charAt(0);
				break;
			default:
				System.out.print("Error");
				break;
			}
		}
	}

	private static void printElements(ArrayList list) {
		// output elements using iterator
		Iterator<String> iter = list.iterator();
		while (iter.hasNext()) {
			System.out.println(iter.next());
		}
	}

	public static void main(String[] args) {
		Scanner reader = new Scanner(System.in);
		ArrayList<String> cars = new ArrayList<String>();

		cars.add("BMW");
		cars.add("Mercedes");
		cars.add("Ferrari");

		// print elements before adding or removing
		printElements(cars);

		System.out.print("Add or remove item? (a / r) ");
		char selection = reader.nextLine().charAt(0);

		addOrRemoveElements(selection, reader, cars);

		// print elements after adding or removing
		printElements(cars);
	}
}
Output
BMW
Mercedes
Ferrari
Add or remove item? (a / r) r
Please enter element to remove: BMW
continue removing? (y / n) y
Please enter element to remove: Bugatti
Element not found!
continue removing? (y / n) n
Mercedes
Ferrari