【发布时间】:2019-01-15 07:17:18
【问题描述】:
所以这是针对硬件问题的。这是 1 到 10 之间数字的猜谜游戏。我必须创建两个异常类: 1.处理猜测 2.如果用户超过5次猜测
如果用户输入的格式不正确,还有第三个要求(但这并不要求我创建额外的异常类。
我的问题是,我希望用户无论输入什么内容,都可以尝试 5 次,无论是 5 次还是 15 次。我可以对超出范围的任何猜测执行此操作,但是当我输入无效格式时,如“五”循环变为无限。我究竟做错了什么?提前致谢:
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
final int MAX_ATTEMPTS = 5; // Stores maximum number of attempts
int answer; // Stores answer
int attempts = 1; // Stores nubmer of attempts
int guess; // Stores user's guess
boolean checkAnswer = true; // Loop control variable
// Create Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
// Generate random nubmer between 1 and 10
answer = generateNumber();
/**
* Allow user to guess (up to five times) what the random number is. Includes
* exception handling for guesses that are outside of the range of 1 and 10,
* have exceeded 5 guesses, and are invalid formats and/or data types.
**/
while (checkAnswer) {
try {
// Prompt user for input
System.out.println("Please guess a number between 1 and 10");
System.out.println("HINT: " + answer);
guess = keyboard.nextInt();
// Throw exception if user exceeds 5 guesses
if (attempts > MAX_ATTEMPTS)
throw new TooManyGuessesException(attempts);
// Throw exception if user guesses outside of range
else if ((guess > 10) || (guess < 1))
throw new BadGuessException(guess);
// Prompt user that guess is correct and exit loop
else if (guess == answer) {
if (attempts == 1)
System.out.println("YOU WIN!! Wow!! You made "
+ attempts
+ " attempt and guessed it on the "
+ "first try!");
else
System.out.println("YOU WIN!! You made " + attempts + " attempts");
checkAnswer = false;
} else {
attempts++; // increment attempts if no correct guess
}
}
// Handles guesses that are outside of range
catch (BadGuessException e) {
attempts++;
System.out.println(e.getMessage());
continue;
}
// Handles exception if user exceeds maximum attempts
catch (TooManyGuessesException e) {
checkAnswer = false;
System.out.println(e.getMessage());
}
// Handles exception if user enters incorrect format
catch (Exception e) {
attempts++;
System.out.println("Sorry, you entered an invalid number " + "format.");
break;
}
}
}
/**
* <b>generateNumber method</b>
* <p>
* Generates and returns 1 random number between 1 and 10 inclusive
* </p>
*
* @return A random number between 1 and 10 inclusive.
*/
public static int generateNumber() {
int randomNumber; // Store lotto number 1
final int RANGE = 10; // Sets range of random number
// Create random object
Random rand = new Random();
// Generate a random value
randomNumber = rand.nextInt(RANGE) + 1;
return randomNumber;
}
}
【问题讨论】:
-
我不清楚您的要求。您是否希望用户即使输入无效格式(例如“五”)也尝试 5 次?
-
实际上你的程序在进入
catch(Exception e)之后就结束了,因为你打破了循环。 -
无关:请始终使用 { 大括号 },即使对于单个 if/else 块也是如此。这些东西很容易出错,所以总是使用完整的块。
-
无论任务背后的动机是什么(家庭作业、摆弄或生产性代码),对控制流使用异常总是不好的做法。
标签: java while-loop exception-handling