-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPhoneBook.java
More file actions
88 lines (80 loc) · 2.6 KB
/
PhoneBook.java
File metadata and controls
88 lines (80 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import java.util.*;
class Contact{
String name;
String number;
Contact(String name, String number){
this.name = name;
this.number = number;
}
}
public class PhoneBook {
static ArrayList<Contact> contacts = new ArrayList<>();
// Add new contacts
public static void addContacts(String name, String number){
contacts.add(new Contact(name, number));
System.out.println("✅Contact added successfully!");
}
// Showing all contacts (sorted by name)
public static void showContact(){
if(contacts.isEmpty()){
System.out.println("❌No contacts found!");
return;
}
Collections.sort(contacts, Comparator.comparing(c -> c.name.toLowerCase()));
System.out.println("\n--- Contact List---");
for(Contact c : contacts){
System.out.println("Name:" + c.name+ ", Number:" + c.number);
}
}
//Searching by name
public static void searchContact(String name){
boolean found = false;
for(Contact c : contacts){
if(c.name.equalsIgnoreCase(name)){
System.out.println("✅Found: "+ c.name + " -> "+ c.number);
found = true;
break;
}
}
if(!found){
System.out.println("❌Contact not found!");
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int choice;
do{
System.out.println("\n📞 Phonebook Menu:");
System.out.println("1. Add Contact");
System.out.println("2. Show Contacts");
System.out.println("3. Search Contact");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = in.nextInt();
in.nextLine();
switch (choice) {
case 1:
System.out.print("Enter Name: ");
String name = in.nextLine();
System.out.print("Enter number: ");
String number = in.nextLine();
addContacts(name, number);
break;
case 2:
showContact();
break;
case 3:
System.out.print("Enter Name to Search: ");
String searchName = in.nextLine();
searchContact(searchName);
break;
case 4:
System.out.println("👋 Exiting...");
break;
default:
System.out.println("❌Invalid choice!");
}
} while(choice!=4);
in.close();
}
}