Java while循环跳过用户输入的第一次迭代

Java while循环跳过用户输入的第一次迭代,java,while-loop,io,java.util.scanner,next,Java,While Loop,Io,Java.util.scanner,Next,我正在制作一个游戏,目前我需要为“英雄”设定名字!这要求玩家输入英雄的名字。 问题是,当它在控制台中询问英雄1的名字时,它只是跳过并直接转到英雄2。 如果我使用.next而不是.nextLine,它会工作,但它会将任何带有空格的名称解释为两个不同的名称 这里是代码,希望有意义!提前感谢大家: public void heroNames() //sets the name of heroes { int count = 1; while (count <= numHeroes

我正在制作一个游戏,目前我需要为“英雄”设定名字!这要求玩家输入英雄的名字。 问题是,当它在控制台中询问英雄1的名字时,它只是跳过并直接转到英雄2。 如果我使用.next而不是.nextLine,它会工作,但它会将任何带有空格的名称解释为两个不同的名称

这里是代码,希望有意义!提前感谢大家:

public void heroNames() //sets the name of heroes
{
    int count = 1;
    while (count <= numHeroes)
    {
        System.out.println("Enter a name for hero number " + count);
        String name = scanner.nextLine(); 
        if(heroNames.contains(name)) //bug needs to be fixed here - does not wait for user input for first hero name
        {
            System.out.println("You already have a hero with this name. Please choose another name!");
        }
        else
        {
            heroNames.add(name);
            count++; //increases count by 1 to move to next hero
        }
    }
}
如果使用Scanner.nextInt读取numheros,则换行符保留在其缓冲区中,因此以下Scanner.nextLine返回一个空字符串,这实际上导致两个连续的Scanner.nextLine序列以获取第一个英雄名称

在下面的代码中,我建议您使用Integer.parseIntscanner.nextLine读取英雄的数量,作为一种风格,不要使用局部变量计数,因为它隐式地绑定到heroNames集合的大小:

Scanner scanner = new Scanner(System.in);
List<String> heroNames = new ArrayList<>();

int numHeroes;

System.out.println("How many heroes do you want to play with?");

while (true) {
    try {
        numHeroes = Integer.parseInt(scanner.nextLine());
        break;
    } catch (NumberFormatException e) {
        // continue
    }
}

while (heroNames.size() < numHeroes) {
    System.out.println("Type hero name ("
            + (numHeroes - heroNames.size()) + "/" + numHeroes + " missing):");
    String name = scanner.nextLine();
    if (heroNames.contains(name)) {
        System.out.println(name + " already given. Type a different one:");
    } else if (name != null && !name.isEmpty()) {
        heroNames.add(name);
    }
}

System.out.println("Hero names: " + heroNames);

在循环之前添加scanner.nextLine。从循环中创建名称字符串,并将其分配给扫描仪的返回。可能重复