Java 如何在循环中生成递增整数值 对于(int i=0;i

Java 如何在循环中生成递增整数值 对于(int i=0;i,java,Java,您可以使用i变量: for (int i = 0; i <= numOfPlayers; i++) { System.out.println("What is your name? "); String name = scan.next(); System.out.println("Choose a color (Red, blue, green, yellow)"); String color = scan.next(); int id = play

您可以使用i变量:

for (int i = 0; i <= numOfPlayers; i++)
{    
   System.out.println("What is your name? ");
   String name = scan.next();
   System.out.println("Choose a color (Red, blue, green, yellow)");
   String color = scan.next();
   int id = players.add(new Player(name, id, color));
}
for(int i=0;i
for(int i=0;i
int id=0;//如果将id持久化到DB中,则替换为获取最新id的函数

对于(int i=0;i),您可能需要考虑改变这一行:

int id = 0; // If you persist the IDs in DB, replace with a function to get the latest id
for (int i = 0; i <= numOfPlayers; i++) {
    System.out.println("What is your name? ");
    String name = scan.next();
    System.out.println("Choose a color (Red, blue, green, yellow)");
    String color = scan.next();
    id++;
    players.add(new Player(name, id, color));
// Using variable i like sayd @Patrícia Espada
for (int i = 0; i <= numOfPlayers; i++) {
    System.out.println("What is your name? ");
    String name = scan.next();
    System.out.println("Choose a color (Red, blue, green, yellow)");
    String color = scan.next();
    players.add(new Player(name, (i+1), color));
对这些:

int id = players.add(new Player(name, id, color));
你也可以写一行而不是我写的两行:

玩家。添加(新玩家(姓名、i+1、颜色))


因为创建
int-id
在这个循环中似乎是完全多余的。

你的意思是你想要
int-id=i;
玩家。添加(新玩家(名字,i+1,颜色));
因此这将等于玩家的数量,例如,在arraylist的索引2中添加的玩家的id将为3?如果要使用id作为添加的玩家数量的计数器,请使用
int id=i+1;
。在循环的第一次迭代中,玩家的id将为0。但您可以按照自己的意愿操作变量。例如正如VPK所提到的,将id设置为i+1。
int id = 0; // If you persist the IDs in DB, replace with a function to get the latest id
for (int i = 0; i <= numOfPlayers; i++) {
    System.out.println("What is your name? ");
    String name = scan.next();
    System.out.println("Choose a color (Red, blue, green, yellow)");
    String color = scan.next();
    id++;
    players.add(new Player(name, id, color));
// Using variable i like sayd @Patrícia Espada
for (int i = 0; i <= numOfPlayers; i++) {
    System.out.println("What is your name? ");
    String name = scan.next();
    System.out.println("Choose a color (Red, blue, green, yellow)");
    String color = scan.next();
    players.add(new Player(name, (i+1), color));
int id = players.add(new Player(name, id, color));
int id = i; // assigning value of "i", that is incremented in each loop, to "id"
players.add(new Player(name, id, color)); // adding new Player to players list using incremented value of "id"