电话号码管理及查询程序Java代码
时间: 2024-01-01 11:04:06 浏览: 84
以下是一个简单的电话号码管理及查询程序Java代码,供参考:
```java
import java.util.HashMap;
import java.util.Scanner;
public class Phonebook {
private HashMap<String, String> phonebook;
public Phonebook() {
phonebook = new HashMap<>();
}
public void addEntry(String name, String phone) {
phonebook.put(name, phone);
}
public void removeEntry(String name) {
phonebook.remove(name);
}
public String lookupNumber(String name) {
return phonebook.get(name);
}
public static void main(String[] args) {
Phonebook phonebook = new Phonebook();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("1. Add entry\n2. Remove entry\n3. Lookup number\n4. Exit");
int choice = scanner.nextInt();
scanner.nextLine(); // consume newline
switch (choice) {
case 1:
System.out.print("Enter name: ");
String name = scanner.nextLine();
System.out.print("Enter phone number: ");
String phone = scanner.nextLine();
phonebook.addEntry(name, phone);
System.out.println("Entry added.");
break;
case 2:
System.out.print("Enter name: ");
name = scanner.nextLine();
phonebook.removeEntry(name);
System.out.println("Entry removed.");
break;
case 3:
System.out.print("Enter name: ");
name = scanner.nextLine();
phone = phonebook.lookupNumber(name);
if (phone != null) {
System.out.println("Phone number: " + phone);
} else {
System.out.println("Entry not found.");
}
break;
case 4:
System.exit(0);
default:
System.out.println("Invalid choice.");
}
}
}
}
```
该代码使用了HashMap来存储电话号码,提供了添加、删除和查询电话号码的功能。用户可以通过输入数字选择不同的操作,程序会根据用户的选择进行相应的操作。
阅读全文