Java扫描器允许一定数量的INT
真的很难找到答案
我正在创建一个游戏,它询问有多少玩家,用户可以输入的最大玩家数是3(1、2或3)。这是在创建for循环还是在scanner函数中输入一个参数
下面的代码:
System.out.println(" How many players are there? ");
int numberOfPlayers = scan.nextInt();
Player[] players = new Player[numberOfPlayers]; //this is where the players scores are stored
int currentPlayer = 0; //because arrays start at 0: +1 is added
for (int i = 0; i < numberOfPlayers; i++) {
System.out.println("What is player " + (i + 1) + " called?");
String playerName = scan.next();
players[i] = new Player(playerName);
# 1 楼答案
我建议将
Integer.parseInt(scan.nextLine())
与循环一起使用,例如:因此,如果用户输入了错误的数字或数字
> 3
或< 1
,它将要求用户再次输入数字,直到用户输入正确的数字1,2,3