I am basically writing a hangman game and I have the program read these four letter words from a .txt file I have. I have copied the .class and the .txt files over in to the src folder for the program and it still prints out the "File not found." that I have written in my RandomWordProvider class. Here is the code:
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;
}
}
So obviously it is doing the "try" but it isn't working and it's just doing the file not found, but I don't know why. Can someone help me?