2017-03-02 90 views
0

我目前正在做一个阿克曼功能问题,我们必须在用户输入的失效保护中进行编码。因此,如果用户输入通常会导致程序崩溃,它只会发送一条消息。我能够找出例外,如果整数值太大,但我不知道如何检查用户输入是否是一个整数。我试过尝试并用“InputMismatchException”捕获块,但是代码开始混乱并且出错或者不起作用。Ackermans的功能尝试抓取问题

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



} 

}

回答

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