已抛出的FileNotFoundException

时间:2016-02-07 00:10:09

标签: java exception compiler-errors

我在这里有一个小代码(整体的一部分)用于一个刽子手游戏以及它在编译时给出的错误。

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文件与程序在同一个文件夹中,而selectSecretWord()方法在main函数(用于测试它)中工作。我怀疑它是一个PATH问题,但不知道如何解决它。提前感谢您的任何帮助。

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

在方法chooseSecretWord()中抛出FileNotFoundException。并使用constrouctor中的方法。所以你必须这样做:

public Hangman() throws FileNotFoundException{
     ....
}

或在constrouctor中捕捉它。