绕过试试捕获

时间:2013-11-29 14:36:59

标签: java loops exception try-catch

在下面的代码中,我试图允许程序捕获来自用户的无效输入的异常,但仍然允许程序在捕获异常后循环回到方法的开头。但是在我的例子中,一旦有异常,程序就会终止。我怎么能纠正这个?非常感谢!

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

4 个答案:

答案 0 :(得分:0)

我不太确定异常部分,但您是否可以使用if语句?

Scanner有一个方法“hasNextInt”,可用于检查输入是否为na int。例如:

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

很抱歉,它实际上并没有直接回答你的问题,但我想你也可能想知道这种可能的方式。 :)

答案 1 :(得分:0)

您可以使用方法hasNextInt(),而不是抛出异常,如果令牌是数字,则返回true。  但是如果你想绝对使用try catch块,你必须删除scanner.next()instrsctions,因为当缓冲区上有nothings时,它会抛出NoSuchElementException

答案 2 :(得分:0)

我认为我给出的解决方案可以改进,但这是修改代码的简单修改:(只需添加新的条件变量来检查是否需要进一步的输入/ ans尝试)

希望它有所帮助 - 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);

    }
}

答案 3 :(得分:0)

如果您想拥有以下内容:

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

应该使用以下内容替换内部do-while循环:

            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);
相关问题