private static int getNumberOfPlayers() {
System.out.println("Please enter number of players ");
Scanner sc = new Scanner(System.in);
int numOfPlayers = sc.nextInt();
System.out.println("You have selected " + numOfPlayers + " Players");
// controlling input, at least 2 - at most 4 players can play the game
while (numOfPlayers < MIN_NUM_PLAYERS || numOfPlayers > MAX_NUM_PLAYERS) {
System.out.print("Please enter a number between 2 and 4: ");
numOfPlayers = sc.nextInt();
System.out.println("You have selected " + numOfPlayers + " players");
}
return numOfPlayers;
}
当玩家输入并在此处进入其他任何内容时,游戏崩溃了。我希望Sout消息告诉用户和回路,以便他们可以重试而不是崩溃。有人可以帮助我修改此方法以实现此功能。任何帮助将不胜感激。
只需这样的异常刻板即可。这可能就是您想要的:
private static int getNumber() {
System.out.println("Please enter number of players ");
Scanner sc = new Scanner(System.in);
int numOfPlayers = sc.nextInt();
System.out.println("You have selected " + numOfPlayers + " Players");
int newNumOfPlayers;
// controlling input, at least 2 - at most 4 players can play the game
while(true){
if (numOfPlayers < MIN_NUM_PLAYERS || numOfPlayers > MAX_NUM_PLAYERS) {
System.out.print("Please enter a number between 2 and 4: ");
try{
newNumOfPlayers = sc.nextInt();
}catch(Exception ex){
System.out.println("Please select a number only");
sc.next();
continue;
}
numOfPlayers = newNumOfPlayers;
System.out.println("You have selected " + numOfPlayers + " players");
return numOfPlayers;
}
}
}