如何在循环中创建增量器整数值

时间:2018-01-09 12:26:46

标签: java

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));
}

我试图这样做,id号等于一个递增的数字,每增加​​一个新玩家就会增加。我怎么能这样做?

4 个答案:

答案 0 :(得分:0)

您可以使用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 = i;
    players.add(new Player(name, id, color));
}

答案 1 :(得分:0)

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 = i+1;
    players.add(new Player(name, id, color));
}

make i + 1,而我的问题将被解决..

答案 2 :(得分:0)

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));

答案 3 :(得分:0)

您可能需要考虑更改此行:

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" 

你也可以写一行而不是我写的两行:

players.add(new Player(name, i + 1, color))

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