A first complete program: one data structure, a few commands and clear messages.
What to build
A contact book with add, find, delete and list commands.
Requirements
- Commands:
add NAME PHONE(printexists NAMEif the name is already there),find NAME(printNAME: PHONEorunknown NAME),delete NAME(printunknown NAMEif absent),list(printNAME: PHONEfor every contact in alphabetical order, orempty).
Input
Line 1: q. Then q commands; names and phones are single words.
Output
One line per message, find and listed contact.
Constraints
1 ≤ q ≤ 200.
Example
Input:
5
add Rina 555-1
add Arif 555-2
find Rina
add Rina 555-9
list
Output:
Rina: 555-1
exists Rina
Arif: 555-2
Rina: 555-1
Why it works
A sorted map gives each name one phone, checks for existence directly, and lists the contacts in order without sorting.
Examples
Example 1 · Input
5 add Rina 555-1 add Arif 555-2 find Rina add Rina 555-9 list
Expected output
Rina: 555-1 exists Rina Arif: 555-2 Rina: 555-1
Example 2 · Input
3 find Zoya delete Zoya list
Expected output
unknown Zoya unknown Zoya empty
Hints
Hint 1
A TreeMap<String, String> from name to phone keeps the list sorted.
Hint 2
Check whether the name exists before adding or deleting.
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());
Map<String, String> contacts = new TreeMap<>();
for (int i = 0; i < q; i++) {
String[] p = in.nextLine().split(" ");
switch (p[0]) {
case "add" -> {
if (contacts.containsKey(p[1])) System.out.println("exists " + p[1]);
else contacts.put(p[1], p[2]);
}
case "find" -> System.out.println(contacts.containsKey(p[1]) ? p[1] + ": " + contacts.get(p[1]) : "unknown " + p[1]);
case "delete" -> {
if (contacts.remove(p[1]) == null) System.out.println("unknown " + p[1]);
}
default -> {
if (contacts.isEmpty()) System.out.println("empty");
for (Map.Entry<String, String> e : contacts.entrySet()) System.out.println(e.getKey() + ": " + e.getValue());
}
}
}
}
}