gpt4 book ai didi

java - 如何实现猜谜游戏的自定义异常

转载 作者:行者123 更新时间:2023-11-30 02:04:14 25 4
gpt4 key购买 nike

我必须创建一个最多允许 5 轮的猜谜游戏,并且用户输入必须在 1 到 10 之间(包含 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 block (以及 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.");
}
}
}

最佳答案

@Jack Flamp 刚才说的是完全正确的,但你不想检查猜测是否在 1 到 10 之间(含),而是检查用户猜测是否与你的随机数匹配。

if (guess == n) {
System.out.println("YOU WIN!\nIt took you " + turn + " attempts.");
} else {
throw new BadGuessException();
}

如果您希望在turn变量超过5时抛出异常,请将其从while条件中删除,并在while范围的开头创建一个if:

if (turn > 5)
throw new TooManyGuessesException();

PS:在 while 范围内加上括号,否则您将立即遇到 TooManyGuessesException

PS2:我想评论 Jack Flamp 的消息,但由于我的声望还没有 50,所以我不能。

关于java - 如何实现猜谜游戏的自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51828834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com