[英]How to prevent my app from crashing when there is no input or if input is invalid
[英]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
抛出InputMismatchException
。 此异常会导致程序崩溃。 使用 try-catch 块来处理此异常,以免它影响您的程序:
try {
int move = input.nextInt();
System.out.print(move);
}
catch (InputMismatchException e) {
System.out.print("error: not a number");
}
try-catch 块是一个方便的工具,用于捕获运行代码时可能发生的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.