真的很难找到答案。
我创建了一个游戏,它会询问有多少玩家,用户可以输入的最大玩家数量是3(1,2或3)。这是创建for循环还是我可以在扫描仪功能中输入参数?
以下代码:
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);
答案 0 :(得分:0)
您可以使用Scanner的nextLine()来读取换行符而不是next()
,如下所示:
System.out.println(" How many players are there? ");
int numberOfPlayers = Integer.parseInt(scan.nextLine());
Player[] players = new Player[numberOfPlayers];
for (int i = 0; i < numberOfPlayers; i++) {
System.out.println("What is player " + (i + 1) + " called?");
String playerName = scan.nextLine();
players[i] = new Player(playerName);
}
答案 1 :(得分:0)
我建议将Integer.parseInt(scan.nextLine())
与循环一起使用,例如:
int numberOfPlayers = 0;
boolean correct = false;
do {
try {
System.out.println(" How many players are there? ");
numberOfPlayers = Integer.parseInt(scan.nextLine());
if (numberOfPlayers >= 1 && numberOfPlayers <= 3) {
correct = true;
}
} catch (NumberFormatException e) {
}
} while (!correct);
因此,如果用户输入错误的号码或号码> 3
或< 1
,则会要求用户再次输入号码,直到用户输入正确的号码1,2,3