0

I am making a game and currently I need to set the names for the 'heroes'! This requires the player to enter a name for the heroes. The thing is, when it asks for the name of hero 1 in the console, it just skips over and goes straight to hero 2. If I use .next() instead of .nextLine(), it works, but it interpreted any names with a space in them as two different names!

Here is the code, I hope that make sense! Thanks all in advance :)

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

1 Answers1

1

If you read numHeroes with Scanner.nextInt a newline character remains in its buffer and thus an empty string is returned by the following Scanner.nextLine, effectively resulting in a sequence of two consecutive Scanner.nextLine() to get the first hero name.

In the following code I suggest you read the number of heroes with Integer.parseInt(scanner.nextLine) and, as a matter of style, don't use a local variable count since it's implicitely bound to the size of the heroNames collection:

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);
Raffaele
  • 19,761
  • 5
  • 42
  • 81