i当前在做一个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!");
}
}
}
您必须放置
int n = answer.nextInt();
在尝试块中。然后,您可以捕获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!");
}
}