Your first ArrayList: add, remove and print items as commands arrive.
What to build
A shopping list driven by commands.
Requirements
- Commands:
add ITEM(append),remove ITEM(remove the first match, or printno ITEMif there is none),print(printN: ITEM, ITEM, ...with the number of items, or0: empty).
Input
Line 1: q. Then q commands; items are single words.
Output
One line per print and per failed removal.
Constraints
1 ≤ q ≤ 100.
Example
Input:
5
add milk
add eggs
print
remove milk
print
Output:
2: milk, eggs
1: eggs
Why it works
An ArrayList grows with each add and keeps the order, and remove reports whether it found the item, which is exactly what the commands need.
Examples
Example 1 · Input
5 add milk add eggs print remove milk print
Expected output
2: milk, eggs 1: eggs
Example 2 · Input
3 remove tea print add tea
Expected output
no tea 0: empty
Hints
Hint 1
Keep the items in an ArrayList<String>; remove(Object) removes the first matching item and returns whether it found one.
Hint 2
String.join(", ", list) joins the items.
Solution
Show one correct solution (try it yourself first)
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int q = Integer.parseInt(in.nextLine().trim());
List<String> items = new ArrayList<>();
for (int i = 0; i < q; i++) {
String[] p = in.nextLine().split(" ");
if (p[0].equals("add")) {
items.add(p[1]);
} else if (p[0].equals("remove")) {
if (!items.remove(p[1])) System.out.println("no " + p[1]);
} else {
System.out.println(items.size() + ": " + (items.isEmpty() ? "empty" : String.join(", ", items)));
}
}
}
}