首页 > 解决方案 > 如何防止程序因输入错误而崩溃

问题描述

当我在 1 到 9 之间选择一个数字并在控制台中输入一个数字时,该方法确实有效并做出了正确的移动。但我的问题是如何避免程序在我输入字母而不是数字时崩溃。

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

   }
}

标签: javainput

解决方案


每个nextXYZ方法都有一个等效的hasNextXYZ方法,可以让您检查其类型。例如:

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

推荐阅读