当我选择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");
}
}
}
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块是一个方便的工具,用于捕获运行代码时可能发生的错误。
每个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");