2017-03-02 88 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!"); 
    } 
}