我正在做家庭作业 (Hangman)。它已经完成,但我需要添加一个异常(exception)并且遇到困难。明天到期,但我仍然没有收到导师的消息,所以我想我会在继续等待的同时在这里发帖。作业要求:
public boolean guessCharacter(char guess) throws Exception - This method returns whether a given character is a part of the key phrase. If the guessed character is valid, then this method should return true, false otherwise. You should throw an exception if the guess has been guessed before (which can be taken care of by the code that is calling this method).
我假设我需要在工作类方法中抛出异常并在调用该方法的工作类中处理它。我搜索了 SO 并发现了这个:
Keep a reference to your workers in your GUI and in your workes add a try catch. In the catch assign the exception to a variable and add a getter to it. IN your GUI, when your worker is done, just check if there is an exception in the worker or not.
这看起来像我需要做的,但我不确定如何实现它。我想要一个代码示例。这是我目前所拥有的(guessedLetters 是一组):
public boolean guessCharacter(char guess) throws Exception
{
// Reset index
if (index == keyPhrase.length())
index = 0;
// Determine if guessed letter is part of word
if (guess == keyPhrase.charAt(index))
{
isValid = true;
boardArray[index] = guess; // If it is, place it correctly in array
try {
// SOME TYPE a = guessedLetters.add(Character.toString(guess));
} catch (Exception e) {
// a = not sure what to do here;
}
} else
isValid = false;
index++;
return isValid;
}
应该注意的是,我根据单词的长度多次调用此方法,以检查用户对单词中每个字母的猜测。我敢肯定有一种更优雅的方式,我只是还没有想出一个。我也不确定对驱动程序类中的 boolean 结果有什么用处。
提前致谢!
最佳答案
您不应该在尝试的地方捕获异常,而应该抛出异常。
由于这是家庭作业,因此这是指导而非实际代码:
首先,检查集合以查看字母是否已被猜出。如果它已经存在于集合中,则抛出异常(throw new Exception("That letter has already been guessed!"
)。否则,将该字母添加到集合中,并照常继续。
如您的作业所述,此异常将“由调用此方法的代码处理”。在您演示的 guessCharacter
方法中,您只需在需要时抛出适当的异常(由于重复猜测)。
关于Java:捕获Driver类中Worker类抛出的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15049153/