gpt4 book ai didi

java - 当我的文件位于正确的文件夹中时,为什么我一直从我的 catch 异常中获取 "File not found."?

转载 作者:行者123 更新时间:2023-11-30 11:11:04 25 4
gpt4 key购买 nike

我基本上是在写一个刽子手游戏,我让程序从我的 .txt 文件中读取这四个字母的单词。我已将 .class 和 .txt 文件复制到程序的 src 文件夹中,它仍然打印出“找不到文件”。我在我的 RandomWordProvider 类中写的。这是代码:

public class WordGuessingGame {

static class RandomWordProvider {

private final List<String> words;

public RandomWordProvider() {
words = readFile();
}

private 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 {
String fileName = "FourLetterWords.txt";
File fourLetterWords = new File(fileName);
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.equals("Yes") || playerAnswer.equals("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!");
}
if (playerAnswer.equals("No") || playerAnswer.equals("no")) {
System.out.print("Maybe another time!");
}
RandomWordProvider randomWordProvider = new RandomWordProvider();
PlayerCharacterEntry playerCharacterEntry = new PlayerCharacterEntry();

String playerInput;
String randomWord;


}
}

很明显它在做“尝试”,但它没有工作,它只是在做找不到的文件,但我不知道为什么。有人可以帮助我吗?

最佳答案

如果您不想指定硬编码路径,这里是从您的类路径获取文件的想法:

        try {
URL url = RandomWordProvider.class.getResource("FourLetterWords.txt");
File fourLetterWords = new File(url.toURI());
Scanner in = new Scanner(fourLetterWords);
....
}

关于java - 当我的文件位于正确的文件夹中时,为什么我一直从我的 catch 异常中获取 "File not found."?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27551983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com