首页 > 解决方案 > Java 异常处理和循环继续

问题描述

所以这是一个硬件问题。这是一个 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;
    }
}

标签: javawhile-loopexception-handling

解决方案


当您输入“5”时,方法 nextInt() 会抛出 InputMismatchException,然后您进入 catch 块并中断循环。

    catch(Exception e)
    {
        attempts++;
        System.out.println("Sorry, you entered an invalid number "
                + "format.");
        break;
    }

Java 语言规范

14.12.1。while 语句的突然完成 包含的语句的突然完成按以下方式处理:

如果语句的执行由于没有标签的中断而突然完成,则不采取 >进一步的操作并且 while 语句正常完成。

如果语句的执行由于没有标签的 continue 而突然完成,>然后再次执行整个 while 语句。

如果语句的执行由于标签 L 的继续而突然完成,> 那么有一个选择:

如果 while 语句的标签为 L,则再次执行整个 while 语句。

如果 while 语句没有标签 L,则 while 语句会突然完成 > 因为带有标签 L 的 continue。

如果 Statement 的执行由于任何其他原因突然完成,则 while > 语句由于相同的原因而突然完成。

由于标签中断而突然完成的情况由标签语句的一般规则处理(第 14.7 节)。


推荐阅读