java - 如何防止程序因输入错误而崩溃
问题描述
当我在 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);
}
推荐阅读
- excel - 匹配多个条件的两个表中的值
- javascript - 是否可以在 chrome 中打开磁盘上的 .md 文件,进行编辑并保存回磁盘?
- javascript - 引擎字段是必需的,但在 functions\package.json 中找不到
- ios - Xcode 不支持 iOS:找不到设备支持文件
- kubernetes - 如何在 Kubernetes 上定义 localhost
- android-studio - 如果我按照 Flutter 中的指南进行操作,为什么会出现 Gradle 错误?
- css - 我可以有 12.5px 的字体大小吗?
- c# - C# ASPNET 使用 SQL Server 存储过程
- c++ - 无法附加到正在休眠的 Windows 服务
- intellij-idea - Kotlin - DSL 颜色样式