0

I currently doing an Ackerman function problem and we have to code in a fail-safe for the user input. So if the user input that would normally make the program crash, it would instead just send a message. I was able to figure out the exception to if the integer values were too large but I can't figure out how to check if the user input is an integer. I've tried try and catch blocks with an "InputMismatchException" but the code begins to jumble and bug out or just does not work.

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



}

}

spotTop
  • 87
  • 2
  • 7

1 Answers1

0

You have to put

int n = answer.nextInt();

within the try block. Then you may catch java.util.InputMismatchException

This works for me:

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!");
    }
}
kamehl23
  • 522
  • 3
  • 6