本文實現一個控制台交互式電子詞典,支持 單詞中文翻譯查詢 與 輸入 help 導出所有單詞 功能。核心採用 TreeMap 實現單詞有序存儲與 O(log n) 查詢。
詞典文件 doc.txt 採用管道符分隔單詞條,等號分隔鍵值:
hello=你好|man=男人|welcome=歡迎|...
import java.io.*;
import java.util.*;
public class ElectronicDictionary {
private static final String DICT_PATH = "D:/dictionary/doc.txt"; // 路徑按實際情況修改
private final Map dictionary = new TreeMap<>();
/** 加載詞典文件構建索引 */
public void loadDictionary() {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream(DICT_PATH), "GBK"))) {
String line;
while ((line = reader.readLine()) != null) {
parseAndStore(line.trim());
}
System.out.println("詞典加載完成,共 " + dictionary.size() + " 條目");
} catch (IOException e) {
System.err.println("詞典文件讀取失敗: " + e.getMessage());
}
}
private void parseAndStore(String line) {
String[] entries = line.split("\\|");
for (String entry : entries) {
String[] kv = entry.split("=", 2);
if (kv.length == 2) {
dictionary.put(kv[0].trim(), kv[1].trim());
}
}
}
/** 查詢單詞 */
public String lookup(String word) {
return dictionary.get(word);
}
/** 導出所有單詞 */
public void exportAll() {
dictionary.forEach((k, v) -> System.out.println(k + " " + v));
}
/** 主交互循環 */
public void run() {
loadDictionary();
Scanner scanner = new Scanner(System.in);
System.out.println("輸入單詞查詢,輸入 help 導出全部,輸入 exit 退出");
while (scanner.hasNextLine()) {
String input = scanner.nextLine().trim();
if ("exit".equalsIgnoreCase(input)) break;
if ("help".equalsIgnoreCase(input)) {
exportAll();
} else {
String result = lookup(input);
if (result != null) {
System.out.println(result);
} else {
System.out.println("未找到該單詞: " + input);
}
}
}
scanner.close();
}
public static void main(String[] args) {
new ElectronicDictionary().run();
}
}
| 設計決策 | 理由 |
|---|---|
| TreeMap 而非 HashMap | 自動按鍵自然序(字典序)排序,help 導出天然有序,無需額外排序 |
| GBK 編碼讀取 | 兼容中文 Windows 環境下的文本文件編碼 |
| split("=", 2) 限制分割數 | 防止釋義中包含等號導致錯誤分割 |
| try-with-resources | 自動關閉流,防止資源洩漏(JDK 7+) |
輸入單詞查詢,輸入 help 導出全部,輸入 exit 退出
> hello
你好
> man
男人
> help
hello 你好
man 男人
welcome 歡迎
...
> exit
NavigableMap 的 subMap() 實現前綴匹配juniversalchardet 自動識別文件編碼這個迷你項目展示了 Java 集合框架、IO 流處理、編碼處理、控制台交互等基礎技能的綜合運用,是優秀的入門級實戰練習。