Ackermans的功能尝试捕获问题

时间:2017-03-02 06:38:16

标签: java try-catch ackermann

我目前正在处理Ackerman功能问题,我们必须为用户输入编写故障安全代码。因此,如果用户输入通常会导致程序崩溃,那么它只会发送消息。我能够找出异常,如果整数值太大但我无法弄清楚如何检查用户输入是否为整数。我尝试过尝试使用“InputMismatchException”捕获块,但是代码开始混乱并且出错或只是不起作用。

public static void main(String[] args) {

//creates a scanner variable to hold the users answer
Scanner answer = new Scanner(System.in);


//asks the user for m value and assigns it to variable m
System.out.println("What number is m?");
int m = answer.nextInt();




//asks the user for n value and assigns it to variable n
System.out.println("What number is n?");
int n = answer.nextInt();


try{
//creates an object of the acker method
AckerFunction ackerObject = new AckerFunction();
//calls the method
System.out.println(ackerObject.acker(m, n));
}catch(StackOverflowError e){
    System.out.println("An error occured, try again!");
}



}

}

1 个答案:

答案 0 :(得分:0)

你必须把

int n = answer.nextInt();
在try块中

。 然后你可以捕获java.util.InputMismatchException

这对我有用:

public static void main(String[] args) {

    //creates a scanner variable to hold the users answer
    Scanner answer = new Scanner(System.in);

    int m;
    int n;
    try{
        //asks the user for m value and assigns it to variable m
        System.out.println("What number is m?");
        m = answer.nextInt();
        //asks the user for n value and assigns it to variable n
        System.out.println("What number is n?");
        n = answer.nextInt();
    }catch(InputMismatchException e){
        System.out.println("An error occured, try again!");
    }
}
相关问题