用java编写一个程序,程序提供记事本功能:1) 构建记事本类,该类能存储不定数量的记录;能获得已经存储的记录数量;能追加记录;能展示已经存储的全部记录或其中任何一条记录;能删除已经存储的全部记录或其中任何一条记录。2) 构建测试类,该类实现与用户的交互,向用户提示操作信息,并接收用户的操作请求。程序应具有良好的人机交互性能,即:程序应向用户提示功能说明,并可根据用户的功能选择,执行对应的功能,并给出带详细描述信息的最终执行结果。
时间: 2024-02-13 17:02:25 浏览: 56
好的,以下是Java代码实现记事本功能,包括记事本类和测试类。记事本类的实现如下:
```java
import java.util.ArrayList;
import java.util.Scanner;
public class Notepad {
private ArrayList<String> records;
private int count;
public Notepad() {
records = new ArrayList<>();
count = 0;
}
public int getCount() {
return count;
}
public void addRecord(String record) {
records.add(record);
count++;
}
public void showRecords() {
if (count == 0) {
System.out.println("No records found.");
return;
}
System.out.println("All records:");
for (int i = 0; i < count; i++) {
System.out.println((i + 1) + ". " + records.get(i));
}
}
public void showRecord(int index) {
if (index < 1 || index > count) {
System.out.println("Invalid index.");
return;
}
System.out.println("Record " + index + ": " + records.get(index - 1));
}
public void deleteAllRecords() {
records.clear();
count = 0;
System.out.println("All records deleted.");
}
public void deleteRecord(int index) {
if (index < 1 || index > count) {
System.out.println("Invalid index.");
return;
}
records.remove(index - 1);
count--;
System.out.println("Record " + index + " deleted.");
}
}
```
测试类的实现如下:
```java
public class TestNotepad {
public static void main(String[] args) {
Notepad notepad = new Notepad();
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to notepad!");
System.out.println("Available commands: add, show all, show, delete all, delete");
while (true) {
System.out.print("> ");
String command = scanner.nextLine();
if (command.equals("add")) {
System.out.print("Enter record: ");
String record = scanner.nextLine();
notepad.addRecord(record);
System.out.println("Record added.");
} else if (command.equals("show all")) {
notepad.showRecords();
} else if (command.equals("show")) {
System.out.print("Enter index: ");
int index = scanner.nextInt();
scanner.nextLine();
notepad.showRecord(index);
} else if (command.equals("delete all")) {
notepad.deleteAllRecords();
} else if (command.equals("delete")) {
System.out.print("Enter index: ");
int index = scanner.nextInt();
scanner.nextLine();
notepad.deleteRecord(index);
} else {
System.out.println("Unknown command.");
}
}
}
}
```
运行测试类后,用户可以根据提示输入命令,实现记事本的相关功能。例如,输入"add"命令可以添加一条记录,输入"show all"命令可以展示所有记录,输入"show"命令可以展示指定索引的记录,输入"delete all"命令可以删除所有记录,输入"delete"命令可以删除指定索引的记录。
阅读全文