我正在创造一个幸运游戏之轮,我想要包含一个功能,用户输入的数量有多少玩家,而for循环中的构造函数会让很多玩家参与其中。我只是不知道当他们说出他们想要多少玩家时我是如何制作这些物品的
玩家构造函数
public Player(String n) {
money = 0.0;
name = n;
}
问题
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int playerAmount = 0;
do {
if(playerAmount > 5) System.out.println("Thats too many.");
System.out.print("How many players(max 5): ");
playerAmount = kb.nextInt();
} while(playerAmount > 5 || playerAmount == 1);
for(int i = 1; i <= playerAmount; i++) {
System.out.print("Player " + i + " name: ");
String name = kb.next(); // name for the construction of player
Player player1 = new Player(name); // where i want to construct differeing number of different objects
}
}
答案 0 :(得分:0)
简单的解决方案是将每个新玩家添加到列表中:
List<Player> players = new ArrayList<>();
for (int i = 0; i < playerCount; i++) {
players.add(new Player(kb.next()));
}
这可能有点过于复杂,但如果你使用的是Java 8,你也可以使用流习惯用法:
List<Player> players = Stream.generate(kb::next)
.map(Player::new).limit(playerCount).collect(Collectors.toList());
如果您对此不熟悉,则表示使用kb.next()
生成字符串流,使用new Player
将其转换为播放器,将流限制为您想要的播放器数量收集在列表中。