Java单词游戏开发:如何从文件创建并填充DICTIONARY常量?
如何创建单词游戏的DICTIONARY常量
下面是修改后的完整代码,已经实现了DICTIONARY常量的创建,同时修复了原代码中的小问题:
import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; import java.util.InputMismatchException; import java.util.HashSet; import java.util.Set; public class Small_Programming_Assignment { // 定义类级常量DICTIONARY,存储所有词典单词 private static final Set<String> DICTIONARY = new HashSet<>(); // 静态初始化块:类加载时自动执行,加载词典文件内容到DICTIONARY static { String fileName = "dictionary.txt"; File file = new File(fileName); if (!file.isFile()) { System.out.println("Dictionary file cannot be opened"); System.exit(0); } try (Scanner input = new Scanner(file)) { // 使用try-with-resources自动关闭Scanner while (input.hasNextLine()) { String word = input.nextLine().trim(); // 去除单词前后空白字符 if (!word.isEmpty()) { // 跳过空行 DICTIONARY.add(word); } } } catch (FileNotFoundException e) { System.out.println("Dictionary file cannot be opened"); System.exit(0); } } public static void main(String[] args) { // 可选:打印加载的单词数量验证结果 // System.out.println("Loaded " + DICTIONARY.size() + " words into dictionary."); getSelection(); } public static void getSelection() { Scanner sc = new Scanner(System.in); System.out.println(""); System.out.println("Welcome to the Word Games program menu."); System.out.println("Select from one of the following options."); System.out.println("1. Substring problem."); System.out.println("2. Points problem."); System.out.println("3. Exit."); System.out.println("Enter your selection: "); int choice = 0; try { choice = sc.nextInt(); } catch(InputMismatchException e) { System.out.println("Invalid option. Try again."); getSelection(); return; // 递归调用后退出当前方法,避免后续代码执行 } if (choice == 1) { substringProblem(); } else if (choice == 2) { pointsProblem(); } else if (choice == 3) { System.out.println("Goodbye!"); System.exit(0); } else { System.out.println("Invalid option. Try again."); getSelection(); } } public static void substringProblem() { System.out.println("Substring Problem"); // 这里可以直接使用DICTIONARY常量,比如验证单词: // if (DICTIONARY.contains(userInputWord)) { ... } getSelection(); } public static void pointsProblem() { System.out.println("Points Problem"); // 同样可以直接访问DICTIONARY getSelection(); } }
关键改动说明:
- 常量定义:用
static final修饰DICTIONARY,确保它是全局唯一且不可修改的类级常量。选择HashSet是因为它的contains()方法查询效率高,适合后续游戏中验证单词是否存在的场景;如果需要保留单词顺序,可以换成ArrayList。 - 静态初始化块:将词典加载逻辑移到静态块中,程序启动时自动执行,保证
DICTIONARY在任何方法调用前都已初始化完成。使用try-with-resources语法自动关闭Scanner,避免资源泄漏。 - 修复递归逻辑:在
InputMismatchException捕获后添加return,避免递归调用后继续执行当前方法的后续代码。 - 移除冗余代码:删除原main方法中多余的
substringProblem()和pointsProblem()调用,以及重复的FileNotFoundException导入。
现在你可以在substringProblem()和pointsProblem()方法中直接使用DICTIONARY常量,比如验证用户输入的单词是否在词典中。
内容的提问来源于stack exchange,提问作者Gauzl
相关产品推荐
相关产品推荐

