You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

96 lines
3.1 KiB

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class HistoryCommand {
// 使用List<String>存储所有输入的命令
private List<String> commandHistory;
public HistoryCommand() {
this.commandHistory = new ArrayList<>();
}
// 添加命令到历史记录
public void addCommand(String command) {
if (command != null && !command.trim().isEmpty()) {
commandHistory.add(command.trim());
}
}
// 获取所有命令历史
public List<String> getCommandHistory() {
return new ArrayList<>(commandHistory); // 返回副本,防止外部修改
}
// 获取命令数量
public int getCommandCount() {
return commandHistory.size();
}
// 查看指定索引的命令
public String getCommand(int index) {
if (index >= 0 && index < commandHistory.size()) {
return commandHistory.get(index);
}
return null;
}
// 清空命令历史
public void clearHistory() {
commandHistory.clear();
}
// 显示最近的n条命令
public void showRecentCommands(int n) {
int start = Math.max(0, commandHistory.size() - n);
System.out.println("最近 " + (commandHistory.size() - start) + " 条命令:");
for (int i = start; i < commandHistory.size(); i++) {
System.out.println((i + 1) + ". " + commandHistory.get(i));
}
}
// 显示所有命令历史
public void showAllCommands() {
System.out.println("所有命令历史(共 " + commandHistory.size() + " 条):");
for (int i = 0; i < commandHistory.size(); i++) {
System.out.println((i + 1) + ". " + commandHistory.get(i));
}
}
// 命令行交互测试
public static void main(String[] args) {
HistoryCommand history = new HistoryCommand();
Scanner scanner = new Scanner(System.in);
System.out.println("命令历史记录器 - 输入 'exit' 退出,输入 'history' 查看历史记录");
while (true) {
System.out.print("> ");
String input = scanner.nextLine();
// 添加到历史记录
history.addCommand(input);
if ("exit".equalsIgnoreCase(input)) {
System.out.println("退出程序...");
break;
} else if ("history".equalsIgnoreCase(input)) {
history.showAllCommands();
} else if (input.startsWith("history ")) {
try {
int n = Integer.parseInt(input.substring(8).trim());
history.showRecentCommands(n);
} catch (NumberFormatException e) {
System.out.println("无效的数字格式");
}
} else if ("clear".equalsIgnoreCase(input)) {
history.clearHistory();
System.out.println("历史记录已清空");
} else {
System.out.println("执行命令: " + input);
}
}
scanner.close();
}
}