Reputation:
I have a small code (a part of the whole) in here for a hangman game and the error it gives while compiling.
import java.lang.*;
import java.io.*;
import java.util.*;
public class Hangman {
//Properties
private final int MAX_TRIES = 6;
private StringBuffer secretWord;
private StringBuffer allLetters;
private StringBuffer usedLetters;
private int numberOfIncorrectTries;
private int maxAllowedIncorrectTries;
private StringBuffer knownSoFar;
//Constructor
public Hangman()
{
numberOfIncorrectTries = 0;
maxAllowedIncorrectTries = MAX_TRIES;
allLetters = new StringBuffer("abcdefghijklmnopqrstuvwxyz");
usedLetters = new StringBuffer("");
secretWord = chooseSecretWord(); //THIS IS LINE 33
knownSoFar = new StringBuffer("");
for (int count = 0; count < secretWord.length(); count++)
{
knownSoFar.append("*");
}
}
//Methods
public StringBuffer chooseSecretWord() throws FileNotFoundException{
File file = new File("words.txt");
Scanner scanner = new Scanner(file);
final int NUMBER_OF_WORDS;
int counter;
int wordIndex;
NUMBER_OF_WORDS = 99;
StringBuffer[] words = new StringBuffer[NUMBER_OF_WORDS];
//move all words to words array
counter = 0;
while(scanner.hasNext())
{
StringBuffer newWord = new StringBuffer(scanner.next());
words[counter++] = newWord;
}
//Find a random integer to get random index of array
wordIndex = (int)(Math.random()*NUMBER_OF_WORDS);
return words[wordIndex];
}
Error:
1 error found:
File: E:\Java\homeworks\Hangman\Hangman.java [line: 33]
Error: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
I am trying to find the reason for an hour, but wasn't able to see anything. words.txt file is in the same folder with the program and chooseSecretWord() method worked in a main function (which is built to test it). I am suspecting that it is a PATH problem, but not sure how to fix it. Thanks in advance for any kind of help.
Upvotes: 0
Views: 58
Reputation: 11
you throw an FileNotFoundException in method chooseSecretWord(). and use the method in constrouctor.so you must do it :
public Hangman() throws FileNotFoundException{
....
}
or catch it in constrouctor.
Upvotes: 1
Reputation: 2027
The FileNotFoundException is a checked exception which means that you need to catch or throw it. It is up to your design if you are going to throw or catch, but it needs to be done somewhere.
So you can throw here:
public Hangman() throws FileNotFoundException
Or catch here:
allLetters = new StringBuffer("abcdefghijklmnopqrstuvwxyz");
usedLetters = new StringBuffer("");
try {
secretWord = chooseSecretWord();
} catch (FileNotFoundException e) {
// TODO Do something here, example log the error our present a error message to the user.
} //THIS IS LINE 33
knownSoFar = new StringBuffer("");
If you want to know more about exceptions; then, docs.oracle.com has an excellent tutorial about exceptions:
https://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html
Upvotes: 3