我正在制作一个简单的for循环,以遍历ArrayList并向其中添加对象,但是当我输入第一个对象时,什么也没发生。程序似乎没有继续循环。这是我所拥有的:
for (int i = 0; i < (numPlayers.nextInt()-1); i++){
System.out.println("what is player " + (i + 1) + " name?");
Scanner namePlayer = new Scanner(System.in);
String playerName = namePlayer.nextLine();
playerList.add(new Player(playerName));
}
玩家对象的构造函数也非常简单
public Player(String name) {
this.name = name
}
答案 0 :(得分:0)
如果可能,您只需定义一次循环限制:
int numberOfPlayers = numPlayers.nextInt()-1;
for (int i = 0; i < numberOfPlayers; i++){
System.out.println("what is player " + (i + 1) + " name?");
Scanner namePlayer = new Scanner(System.in);
String playerName = namePlayer.nextLine();
playerList.add(new Player(playerName));
}
您需要确保您要循环迭代多次。
答案 1 :(得分:0)
public static void main(String[] args)
{
Scanner numPlayers = new Scanner(System.in);
ArrayList<Player> playerList = new ArrayList<>();
int input = numPlayers.nextInt();
for (int i = 0; i < input; i++){
System.out.println("what is player " + (i + 1) + " name?");
String playerName = numPlayers.next();
playerList.add(new Player(playerName));
}
}
您应该在for循环之外声明scanner
对象。代码的问题是,每次输入字符串后,都需要为(int i = 0; i < (numPlayers.nextInt()-1); i++)
提供一个整数,这就是为什么如果您提供除整数以外的任何内容都会给InputMismatchException
的原因。因此,您必须在for循环外初始化输入常量,否则执行会动态变化。