如何输出字符串并更改该字符串

时间:2018-02-21 23:27:21

标签: java class while-loop class-constructors

你好我想在游戏中创建指定数量的玩家。我已经循环了玩家的创建,但每次循环它应该从制作player1到制作player2我如何构建一个类,我在一个单独的文件中定义了该特定的字符串?

System.out.println("input starting monies in millions of dollaz");
double starterplayermoney = Double.valueOf(keyboard.nextLine());
System.out.println("input total players");
double doubletotalplayers = Double.valueOf(keyboard.nextLine()); 
int i = 1 ;
while(i<=doubletotalplayers){
    String playerstring = "player"+Integer.toString(i);
    player playerstring = new player();
    i++;    
}

2 个答案:

答案 0 :(得分:0)

您应该使用数组或某些播放器集合。问题是你在下一次迭代中覆盖了对玩家对象的引用。

player playerString = new player();

使用这样的数组:

Player [] playerString = new Player [2];
while( i <= doubletotalplayers){
playerString[i] = new Player();

}

另外,我不确定为什么你需要一个玩家数量的双倍值。尝试使用int。

答案 1 :(得分:0)

以下是您的问题的答案:

for (int i=1; i<=doubletotalplayers; i++) {
    String playerstring="Player "+i;
    player playerstring = new player();
}

使用for ()循环可以保存行,这就是我建议使用它的原因,而不是while () {}循环......

现在,如果你真的想保留while () {}循环,那么你需要这样做......

int i = 1 ;
while(i<=doubletotalplayers){
    String playerstring = "player"+i;
    player playerstring = new player();
    i++;    
}