-1

I ran this block of code(see below), and I'm expecting it to prompt the user for the name of the first superhero. However, Instead of taking the input from the user from the first line it immediately goes to the statement after the "else". Here is the console:

How many superheroes would you like?
3
Who is one of the superheroes?
Who is another superhero?
a
Who is another superhero?
b
Thank you
 - 1.68
a - 2.78
b - 5.84

System.out.println("How many superheroes would you like?");
int n = input.nextInt();

String [] Super = new String[n];
for (int i = 0; i < n; i++) {
    if (i == 0) {
        System.out.println("Who is one of the superheroes?");
        Super[i] = input.nextLine();
    } else {
        System.out.println("Who is another superhero?");
        Super[i] = input.nextLine();
    }
Draken
  • 3,049
  • 13
  • 32
  • 49

2 Answers2

1

Try to use Super[i] = input.next(); instead of input.nextLine()

As @achAmháin said if your input has words seperated by spaces you should use:

System.out.println("Who is one of the superheroes?");
input.nextLine();
Super[i] = input.nextLine();
Hülya
  • 3,054
  • 2
  • 10
  • 16
0

As achAmháin commented, the problem is the first nextInt isn't consume the new line character of the input buffer, then when you putting the input.nextLine(); is detecting the character in the buffer and not wait for a new input.

You can fix this, putting after:

int n = input.nextInt();

this:

input.nextLine();

And then work as you expect.

Tested.enter image description here

alexander
  • 51
  • 3