0

This is a snippet of code from a program I am writing:

// User is asked how many options he wants to fill in.
System.out.print("How many options do you have: ");
int numberOfOptions = input.nextInt();

// Array declared for storing user input 
String[] options = new String [numberOfOptions];

// The array options is filled with user input in a for loop.
for(int i = 0; i < numberOfOptions; i++){
    System.out.print("What is option " + (i + 1) + ": ");                
        options[i] = input.nextLine();  
    }                                                                       

This is the output I get when it's executed. As you can see in the screenshot, it prints "What is option..." twice. It doesn't ask for input the first time it prints what is option 1.

I have tried using input.next(). This doesn't give me any problems, it works just fine. It just isn't wat I want because I want the user to be able to input whole sentences instead of only words.

How can I solve this problem, did I do anything wrong?

Piet Pot
  • 15
  • 6

1 Answers1

1

Your probleme is because the first call to nextLine() method is immediately after an nextInt() method which didn't read the newline character, and the first nextLine() read that newline character. The solution is to call a nextLine() after nextInt()

int numberOfOptions = input.nextInt();
input.nextLine();
Younes HAJJI
  • 375
  • 3
  • 20