绕一圈尝试 [英] Looping around a try catch

查看:64
本文介绍了绕一圈尝试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我试图允许程序捕获来自用户的无效输入的异常,但是一旦捕获到异常,仍然允许程序循环回到方法的开头.但是,在我的示例中,一旦出现异常,程序将终止.我该如何纠正?提前非常感谢!

In the below code I am attempting to allow the program to catch an exception for an invalid input from user but still allow the program to loop back to the start of the method once exception has been caught. However in my example once there is an exception the program terminates. How can I rectify this? Thank a lot in advance!

public static void add() {
    // Setting up random
    Random random = new Random();

    // Declaring Integers
    int num1;
    int num2;
    int result;
    int input;
    input = 0;
    // Declaring boolean for userAnswer (Defaulted to false)
    boolean correctAnswer = false;
    do {
        // Create two random numbers between 1 and 100
        num1 = random.nextInt(100);
        num1++;
        num2 = random.nextInt(100);
        num2++;

        // Displaying numbers for user and getting user input for answer
        System.out.println("Adding numbers...");
        System.out.printf("What is: %d + %d? Please enter answer below", num1, num2);
        result = num1 + num2;

        do {
            try {
                input = scanner.nextInt();
            } catch (Exception ex) {
                // Print error message
                System.out.println("Sorry, invalid number entered for addition");
                // flush scanner
                scanner.next();
                correctAnswer=false;
            }
        } while (correctAnswer);

        // Line break for code clarity
        System.out.println();

        // if else statement to determine if answer is correct
        if (result == input) {
            System.out.println("Well done, you guessed corectly!");
            correctAnswer = true;
        } else {
            System.out.println("Sorry incorrect, please guess again");
        }
    } while (!correctAnswer);

}// End of add

推荐答案

如果您要具备以下条件:

If you want to have the following:

1)询问用户x + y多少
2)让用户回答
3)如果答案无效(例如,用户输入"www"),则让用户再次输入对问题1的答案

1) Ask the user how much is x + y
2) Let the user answer
3) If answer is invalid (e.g. user typed in "www"), let the user type his answer to question 1) again

那么您应该将内部do-while循环替换为以下内容:

than you should replace your inner do-while loop with the following:

            boolean validInput = true;
        do {
            try {
                input = scanner.nextInt();
            } catch (Exception ex) {
                // Print error message
                System.out.println("Sorry, invalid number entered for addition. Please enter your answer again.");
                // flush scanner
                scanner.next();
                validInput = false;
            }
        } while (!validInput);

这篇关于绕一圈尝试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆