开发一个Java电话号码查询系统,要求有分支,循环,数组,封装,继承,多态,接口,异常处理
时间: 2024-05-04 08:20:53 浏览: 19
好的,以下是一个基本的Java电话号码查询系统的示例代码,包含了所有要求的特性:
```java
import java.util.Scanner;
interface PhoneNumber {
public void searchNumber(String name);
}
class PhoneBook implements PhoneNumber {
private String[] names = {"Alice", "Bob", "Charlie", "David", "Emma", "Frank"};
private String[] numbers = {"111-111-1111", "222-222-2222", "333-333-3333", "444-444-4444", "555-555-5555", "666-666-6666"};
public void searchNumber(String name) throws Exception {
int index = -1;
for (int i = 0; i < names.length; i++) {
if (names[i].equalsIgnoreCase(name)) {
index = i;
break;
}
}
if (index == -1) {
throw new Exception("Phone number not found.");
} else {
System.out.println("The phone number of " + name + " is " + numbers[index]);
}
}
}
class MobilePhone extends PhoneBook {
public void searchNumber(String name) {
try {
super.searchNumber(name);
} catch (Exception e) {
System.out.println("The phone number of " + name + " is not available.");
}
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
PhoneNumber phoneBook = new MobilePhone();
while (true) {
System.out.print("Enter a name to search (or 'quit' to exit): ");
String name = scanner.nextLine();
if (name.equalsIgnoreCase("quit")) {
break;
} else {
phoneBook.searchNumber(name);
}
}
scanner.close();
}
}
```
这个程序包含了以下特性:
- 分支:在 `main` 方法中使用 `if` 语句判断用户是否想退出程序。
- 循环:在 `main` 方法中使用 `while` 循环来让用户反复查询电话号码。
- 数组:在 `PhoneBook` 类中使用两个数组来存储联系人的姓名和电话号码。
- 封装:在 `PhoneBook` 类中,将 `names` 和 `numbers` 数组设置为私有的,只能通过 `searchNumber` 方法来访问。
- 继承:`MobilePhone` 类继承了 `PhoneBook` 类,并重写了 `searchNumber` 方法。
- 多态:`PhoneNumber` 接口定义了一个 `searchNumber` 方法,`PhoneBook` 类和 `MobilePhone` 类都实现了这个接口,可以通过 `PhoneNumber` 类型的变量来引用这两个类的实例。
- 接口:`PhoneNumber` 接口定义了一个 `searchNumber` 方法,`PhoneBook` 类和 `MobilePhone` 类都实现了这个接口。
- 异常处理:在 `searchNumber` 方法中,如果找不到联系人的电话号码,就抛出一个自定义的异常,`MobilePhone` 类通过 `try-catch` 语句来捕获这个异常,并输出一个友好的提示信息。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)