我这里有一个关于刽子手游戏的小代码(整体的一部分)以及它在编译时给出的错误。
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];
}
错误:
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
我花了一个小时试图找到原因,但什么也没看到。 Words.txt 文件与程序位于同一文件夹中,并且 ChooseSecretWord() 方法在主函数中工作(该函数是为了测试它而构建的)。我怀疑这是一个 PATH 问题,但不知道如何修复它。预先感谢您提供的任何帮助。
最佳答案
FileNotFoundException 是一个受检查的异常,这意味着您需要捕获或抛出它。如果你要扔或接住,这取决于你的设计,但它需要在某个地方完成。
所以你可以在这里抛出:
public Hangman() throws FileNotFoundException
或者在这里捕获:
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("");
如果你想了解更多关于异常的知识;然后,docs.oracle.com 有一个关于异常的优秀教程:
https://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html
关于java - 已经抛出的 FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35248141/