2017-03-02 3 views
0

Ich mache gerade ein Ackerman-Funktionsproblem, und wir müssen einen Fail-Safe für die Benutzereingabe einprogrammieren. Wenn also die Benutzereingabe normalerweise das Programm zum Absturz bringen würde, würde sie stattdessen nur eine Nachricht senden. Ich war in der Lage, die Ausnahme zu finden, wenn die Integer-Werte zu groß waren, aber ich kann nicht herausfinden, wie man überprüft, ob die Benutzereingabe eine Ganzzahl ist. Ich habe versucht, versuchen Blöcke mit einer "InputMismatchException" zu fangen, aber der Code beginnt zu durcheinander und Fehler oder funktioniert einfach nicht.Ackermans 'Funktion Try Catch issue

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



} 

}

Antwort

0

Sie haben

int n = answer.nextInt(); 

im try-Block zu setzen. Dann können Sie fangen java.util.InputMismatchException

Dies funktioniert für mich:

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