-1

so I am creating a TicTacToe game right now and don't really know how to handle anything else but a int. Let's say the user input is a string - the program would throw a error. I actually want it to catch it and say something like "this is not a number between 1 and 9". How can I do this?

int nextPlayerTurn= scan.nextInt();
            while (playerPosition.contains(nextPlayerTurn) ||computerPosition.contains(nextPlayerTurn)
                    || nextPlayerTurn>= 10 || nextPlayerTurn<= 0 ) {
                System.out.println("Position already taken! Please input a valid number (between 1 and 9) ");
                nextPlayerTurn= scan.nextInt();
  • Does this answer your question? [How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner](https://stackoverflow.com/questions/3572160/how-to-handle-infinite-loop-caused-by-invalid-input-inputmismatchexception-usi) – HoRn Jan 15 '21 at 09:47

2 Answers2

0

If you use nextInt() and user enters a String, InputMismatchException will be thrown.

This is a way to handle it:

try {
    scan.nextInt();
}catch (InputMismatchException e) {
    System.err.println("this is not a number between 1 and 9");
}

Note that you will have to reuse nextInt() until the user enters an int

AirlineDog
  • 520
  • 8
  • 21
0

You can either use try catch method or if else conditions.

using if else,

if(scan.hasNextInt()){
    int nextPlayerTurn = scan.nextInt();
    if(nextPlayerTurn < 0 || nextPlayerTurn > 10){
        System.out.println("this is not a number between 1 and 9");
    }else{
        //do something
    }
}else{
    System.out.println("this is not a number between 1 and 9");
}

using try catch,

try{
    int nextPlayerTurn = scan.nextInt();
    if(nextPlayerTurn < 0 || nextPlayerTurn > 10){
        System.out.println("this is not a number between 1 and 9");
    }else{
        //do something
    }
}catch(InputMismatchException e){
    System.out.println("this is not a number between 1 and 9");
}

However, you can also use a method to check the InputMismatchException.
Also check Exception Handling Java

XO56
  • 332
  • 1
  • 12