0

我目前正在做一个阿克曼函数问题,我们必须为用户输入编写一个故障安全代码。因此,如果通常会使程序崩溃的用户输入,它只会发送一条消息。我能够找出整数值是否太大的异常,但我不知道如何检查用户输入是否为整数。我尝试使用“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!");
}



}

}

4

1 回答 1

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!");
    }
}
于 2017-03-02T06:48:32.477 回答