Java异常处理和循环延续

时间:2018-08-08 06:09:51

标签: java while-loop exception-handling

这是针对硬件问题的。这是一个介于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;
    }
}

2 个答案:

答案 0 :(得分:0)

当您输入“五”时,nextInt()方法将引发InputMismatchException,然后您进入catch块并中断循环。

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

Java Language Specification

  

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

     

如果由于没有标签的中断而导致语句的执行突然完成,则不会执行进一步的操作,而while语句将正常完成。

     

如果由于没有标签继续而导致语句的执行突然结束,则>然后再次执行整个while语句。

     

如果由于使用标签L继续而导致语句的执行突然完成,那么可以选择:

     

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

     

如果while语句没有标签L,则while语句会突然完成,因为继续使用标签L。

     

如果由于任何其他原因突然结束了该语句的执行,则出于相同原因而while语句突然结束了。

     

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

答案 1 :(得分:0)

调用nextInt()时,如果下一个数据不是整数,则会出现异常。

注意:这样就不会消耗引起问题的单词,它只会引发异常。

因此,当您重试时,将得到相同的结果。您最有可能希望舍弃其余的文本行。我将向nextLine()添加一个呼叫,以在再次尝试之前阅读该行的其余部分。