我必须创建一个最多允许 5 个回合的猜谜游戏,并且用户输入必须介于 1 和 10 之间。如果不满足这些条件,则可能会引发两个自定义异常(BadGuessException 和 TooManyGuessesException)。我被困在如何进行异常处理上,因为我不确定如何让程序知道是否抛出和捕获这些自定义异常。
我为自定义异常创建了两个类:
public class BadGuessException extends Exception
{
/**
* no-arg constructor
*/
public BadGuessException()
{
super("Sorry, that was an invalid guess!");
}
/**
* parametrized constructor
* @param message String message passed to super class's constructor
*/
public BadGuessException(String message)
{
super(message);
}
}
public class TooManyGuessesException extends Exception
{
/**
* no-arg constructor
*/
public TooManyGuessesException()
{
super("Sorry, too many guesses!");
}
/**
* parametrized constructor
* @param guess integer value representing amount of guesses (turns)
*/
public TooManyGuessesException(int guess)
{
super("Sorry, you guessed " + guess + " times!");
}
}
在下面的代码中,我试图在抛出 TooManyGuessesException 之前允许最多五圈,并且我试图处理小于 1 和大于 10 的数字输入的异常。我只需要一个 try-catch 块(以及 NumberFormatException 的额外 catch 子句)。
import java.util.Random;
import java.util.*;
public class GuessingGame
{
public static void main(String[] args)
{
//Scanner object to receive user input
Scanner keyboard = new Scanner(System.in);
//Create Random class object & random variable
Random rng = new Random();
int n = rng.nextInt(10 - 1 + 1) + 1;
//Create incrementor for guessing turns
int turn = 1;
//Create variable for user input (guess)
int guess;
try
{
while(guess != n && turn <= 5)
System.out.println("Guess a number between 1 and 10 inclusive.");
System.out.println("Hint: the answer is " + n);
guess = keyboard.nextInt();
turn++;
if(guess == n)
{
System.out.println("YOU WIN!\nIt took you " + turn + " attempts.");
}
}
catch(BadGuessException e | TooManyGuessesException e)
{
if(guess < 1 || guess > 10)
e.BadGuessException();
if(turn > 5)
e.TooManyGuessesException();
}
catch(NumberFormatException e)
{
System.out.println("Sorry, you entered an invalid number format.");
}
}
}