Java Word Guess Game检查有效单词



我正在写一个猜字游戏,电脑从txt文件中随机选择一个5个字母的单词。每一轮,玩家都会猜测一个5个字母的单词,如果猜测不正确,计算机会显示该猜测与"秘密"单词有多少个共同字母。

如何检查单词是否在"dictionary"(允许单词的txt文件)中?

 // is word in the dictionary?
 public boolean isValidWord(String word) { 
     //see if string inputted is in the dictionary 
}

有多种方法可以做到这一点:一种是你可以在字典里读一次,按如下方式保存在内存中,然后查找单词是否在中

 Scanner scanner=new Scanner("FileNameWithPath");
 List<String> list=new ArrayList<>();
 while(scanner.hasNextLine()){
     list.add(scanner.nextLine()); 
 }

或者类似地使用BufferedReader:

BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
String str;
List<String> list = new ArrayList<String>();
while((str = in.readLine()) != null){
    list.add(str);
}

现在,您的方法是对列表中的String进行简单检查。

使用java8的新功能!

// read all lines
return !Files.lines(Paths.get(fileName))
    // search matches
    .filter(w -> w.equals(word))
    // any hit?
    .findAny()
    .isEmpty();

最新更新