![](/img/trans.png)
[英]How do I get my Hangman Java file to read a random word in from a .txt file?
[英]How would I call my method to return a random word from a .txt file across a class?
我正在创建一个程序,可以从.txt文件中读取四个字母单词。 玩家在玩游戏时说“是”时,计算机将随机选择一个整数,然后从.txt文件中的该行选择单词。 然后将给玩家7次尝试猜单词的机会。 我遇到的麻烦是能够调用我的RandomWordProvider类中的方法,该方法将返回随机整数,然后返回相应的单词。 这是我所做的:
public class WordGuessingGame2 {
static class RandomWordProvider {
public final List<String> words;
public RandomWordProvider() {
words = readFile();
}
public int randomInteger() {
int randomInt = (int) (Math.random() * words.size());
return randomInt;
}
public String getWord(int randomInt, String line) {
int randomPosition = randomInteger();
String randomWord = words.get(randomPosition);
return randomWord;
}
private List<String> readFile() {
List<String> wordsList = new ArrayList<>();
try {
File fourLetterWords = new File(System.getProperty("user.home"),"Documents/FourLetterWords.txt");
Scanner in = new Scanner(fourLetterWords);
while (in.hasNextLine()) {
String line = in.nextLine();
if (line!=null && !line.isEmpty()) {
wordsList.add(line);
}
}
}
catch (FileNotFoundException ex) {
System.out.println("File not found.");
}
return wordsList ;
}
}
static class PlayerCharacterEntry {
public String playerEntry() {
Scanner characterEntry = new Scanner(System.in);
System.out.print("Enter a character: ");
String playerInput = characterEntry.next();
playerInput = playerInput.toUpperCase();
return playerInput;
}
}
public static void main(String[] args) {
Scanner wantToPlay = new Scanner(System.in);
System.out.print("Welcome to the word guessing game! Would you like to play? ");
String playerAnswer = wantToPlay.next();
if (playerAnswer.equalsIgnoreCase("Yes")) {
System.out.print("\nYour objective is to guess a four letter word by entering"
+ "\nletters on your keyboard. If you can not guess the word in seven attempts,"
+ "\nyou lose! You will be told if the letter you entered is in the word, and"
+ "\nyou will be told if the letter you entered is not in the word. You will be"
+ "\nallowed to guess the word any time during your seven attempts. If at anytime"
+ "\nyou would like to terminate the game, enter the word 'terminate'. Good Luck!"
+ "\n \n");
}
if (playerAnswer.equalsIgnoreCase("No")) {
System.out.print("Maybe another time!");
System.exit(0);
}
RandomWordProvider randomWordProvider = new RandomWordProvider();
PlayerCharacterEntry playerCharacterEntry = new PlayerCharacterEntry();
playerCharacterEntry.playerEntry();
}
}
现在,在底部的底部,我创建了实例,现在试图将我的randomInteger和getWord方法调用到我的main方法中,但是我不知道该怎么做。 我一直对需要包含在getWord方法中的参数感到困惑。 如果有人可以告诉我该怎么做,将不胜感激!
您的第一个问题是,当前的getWord(...)
方法作为公共接口没有意义,因为您依赖于该类来生成随机数并读取文件。 因此,尽管可以,您不必发送此信息; 对于您的配置,它根本行不通,或者没有任何区别。
因此,答案是,您需要一种不带任何参数并返回字符串的方法。 允许您的代码执行所需的操作。
public String getWord() {...}
但是随后在main()
您需要保留字符串一段时间,直到用户用尽所有猜测为止。
String word = randomWordProvider.getWord();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.