我正在尝试用 Java 制作一个简单的刽子手游戏。我确实有一个名为 dictionary.txt 的文本文件,其中包含来自英语词典的 120K 单词。当我要提示用户输入字长并显示具有该特定长度的字数时,就会出现问题。
在这里花了相当多的时间和谷歌搜索后,我已经走到了这一步,但现在我被困住了:
import java.util.Scanner;
import java.io.*;
import java.io.IOException;
public class Hangman
{
public static void main(String[] args) throws IOException
{
// declaring variables
int wordLength;
int guessNumber;
// initiate the scanner
Scanner keyboard = new Scanner( System.in );
// read the dictionary file
File file = new File("dictionary.txt");
StringBuilder contents = new StringBuilder();
BufferedReader reader = null;
// prompt the user for word length
System.out.println("Welcome to Hangman. Let's play! ");
System.out.println("Please enter the desired word length: ");
wordLength = keyboard.nextInt();
while(wordLength < 0 || wordLength > 26)
{
System.out.println("This is not a valid word length. ");
System.out.println("Please enter the desired word length: ");
wordLength = keyboard.nextInt();
}
// prompt the user for number of guesses
System.out.println("How many guesses do you want to have? ");
guessNumber = keyboard.nextInt();
while(guessNumber < 0)
{
System.out.println("Number of guesses has to be a postive integer. ");
System.out.println("Please enter the desired number of guesses: ");
guessNumber = keyboard.nextInt();
}
}
}
我的目标是提示用户输入字长,如果 dictionary.txt 文件中不存在所需的字长,那么它会一直询问,直到给出有效响应。
我还希望能够打印给定单词长度的单词数量(例如,如果用户输入“10”,那么它会显示 dictionary.txt 中有多少单词长度为 10 个字母。
代码的以下部分是我希望用读取 txt 文件并随后执行的代码替换的部分:
while(wordLength < 0 || wordLength > 26)
{
System.out.println("This is not a valid word length. ");
System.out.println("Please enter the desired word length: ");
wordLength = keyboard.nextInt();
}
我可能采取了错误的方法,因此非常欢迎所有反馈!