简体   繁体   中英

How to prevent the programm for crashing because of a wrong input

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

   }
}

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM