Looping around a try catch

痞子三分冷 提交于 2019-12-11 19:53:28

问题


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

回答1:


I'm not quite sure about the exceptions part, but have you maybe though about just using if statements?

Scanner has a method 'hasNextInt' which you can use to check that the the input is na int. For example:

    Scanner scan = new Scanner(System.in);
    int i=0;
    boolean correctAnswer = false;
    while(correctAnswer == false){
        if(scan.hasNextInt()){
            i = scan.nextInt(); correctAnswer = true;
        }else{ System.out.println("Invalid entry");
               correctAnswer = false;
               scan.next();
        }
    System.out.println(i);
    }

Sorry that it doesn't actually directly answer your question, but I though you might want to know about this possible way too. :)




回答2:


Instead of throw an exception maybe you can use the method hasNextInt() which returns true if the token is a number. But if you want absolutely use the try catch block, you have to remove the scanner.next() instrsctions because when nothings available on the buffer, it's throws an NoSuchElementException




回答3:


I think solution i am giving can be improved but this is simple modification to fix your code: (just add new condition variable to check if further input/ans attempts required)

Hope it helps - MAK

public class StackTest {

    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws InterruptedException{
        // 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;
        //MAK: Add new condition for checking need of input
        boolean needAnswer = true;
        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;

            while(needAnswer){
                try {

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

            // 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");
                needAnswer = true;
            }
        } while (!correctAnswer);

    }
}



回答4:


If you want to have the following:

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

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);


来源:https://stackoverflow.com/questions/20288109/looping-around-a-try-catch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!