如何防止程序因输入错误而崩溃

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

当我选择 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");
       }

   }
}

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

我觉得可以这样,'a'还是打印

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() 会抛出 InputMismatchException。此异常导致程序崩溃。使用try-catch块来处理这个异常,这样它就不会影响你的程序:

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

try-catch 块是一个方便的工具,用于捕获 运行 您的代码时可能发生的错误。