Java 阿克曼';函数Try-Catch问题
我目前正在做一个Ackerman函数问题,我们必须为用户输入编写一个故障保护代码。因此,如果用户的输入通常会导致程序崩溃,那么它只会发送一条消息。我能够找出整数值是否太大的例外情况,但我无法找出如何检查用户输入是否为整数。我曾尝试使用“InputMissatchException”捕捉块,但代码开始混乱并出现错误,或者根本不起作用Java 阿克曼';函数Try-Catch问题,java,try-catch,ackermann,Java,Try Catch,Ackermann,我目前正在做一个Ackerman函数问题,我们必须为用户输入编写一个故障保护代码。因此,如果用户的输入通常会导致程序崩溃,那么它只会发送一条消息。我能够找出整数值是否太大的例外情况,但我无法找出如何检查用户输入是否为整数。我曾尝试使用“InputMissatchException”捕捉块,但代码开始混乱并出现错误,或者根本不起作用 public static void main(String[] args) { //creates a scanner variable to hold the
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!");
}
}
}你必须把
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!");
}
}