Home > Back-end >  How to prevent the programm for crashing because of a wrong input
How to prevent the programm for crashing because of a wrong input

Time:10-14

When I choose a number between 1 to 9 and input a number in the console, the method does work and makes the correct move. But my question is how can avoid that the programm gets crashed as soon as I input a letter instead of a number.

public class HumanPlayer {
   static Scanner input = new Scanner(System.in);

   public static void playerMove(char[][] gameBoard) {

       System.out.println("Wähle ein Feld 1-9");
       try {
           int move = input.nextInt();
           System.out.print(move);
           boolean result = Game.validMove(move, gameBoard);
           while (!result) {
               Sound.errorSound(gameBoard);
               System.out.println("Feld ist besetzt!");
               move = input.nextInt();
               result = Game.validMove(move, gameBoard);
           }

           System.out.println("Spieler hat diesen Zug gespielt  "   move);
           Game.placePiece(move, 1, gameBoard);
       } catch (InputMismatchException e) {
           System.out.print("error: not a number");
       }

   }
}

CodePudding user response:

Every nextXYZ method has an equivalent hasNextXYZ method that lets you check its type. E.g.:

int move;
if (input.hasNextInt()) {
    move = input.nextInt();
} else {
    // consume the wrong input and issue an error message
    String wrongInput = input.next();
    System.err.println("Expected an int but got "   wrongInput);
}

CodePudding user response:

i think it can be like this, 'a' still print

System.out.println("expected input: [1-9]");
try {
    int move = input.nextInt();
} catch (Exception e) {
    e.printStackTrace();
    // do something with input not in [1-9]
}
System.out.println("a");

CodePudding user response:

input.nextInt() throws an InputMismatchException when you input a line containing a letter. This exception causes the program to crash. Use a try-catch block to handle this exception so that it does not affect your program:

try {
    int move = input.nextInt();
    System.out.print(move);
}
catch (InputMismatchException e) {
    System.out.print("error: not a number");
}

The try-catch block is a handy tool for catching errors that may occur when running your code.

  • Related