0

I'm trying to prompt the user to type in a string, which will be stored in an array of strings, followed by an inputted int which will be placed into an int array.

I'm running into a problem where the first line is printed, but the user isn't prompted to type in a string. Then the second print statement is immediately printed, and the user is only able to type in an int.

So far I have:

    int i, n = 10;
    String[] sentence = new String[1000];
    int[] numbers = new int[1000];



    for(i = 0; i < n; i++)
        {
        System.out.println("Enter String" + (i + 1) + ":");
        sentence[i] = scan.nextLine();

        System.out.printf("Enter int " + (i + 1) + ":");
        numbers[i] = scan.nextInt();
        }

As output I get:

Enter String 1:
Enter int 1:

Here you can input an int, and it is stored into the int array. But you can't input a String for the String array.

Ples help.

Anon
  • 49
  • 3
  • 3
    Possible duplicate of [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – Nicholas K Feb 02 '19 at 17:37

2 Answers2

2

This problem is caused because of nextInt() method.

Whats happening here is that nextInt() method consumes the integer entered by the user but not the new line character at the end of the user input which is created when you press enter key.

So when you press enter after inputting an integer, next call to nextLine() consumes the new line character which wasn't consumed in the last iteration of the loop by nextInt() method. That's why it skips the input of String in the next iteration of the loop and does't waits for the user to input a String

Solution

You can consume the new line character by calling nextLine() after the nextInt() call

for(i = 0; i < n; i++)
{
    System.out.println("Enter String" + (i + 1) + ":");
    sentence[i] = scan.nextLine();

    System.out.printf("Enter int " + (i + 1) + ":");
    numbers[i] = scan.nextInt();
    scan.nextLine();             // <------ this call will consume the new line character
}
Yousaf
  • 20,803
  • 4
  • 23
  • 45
  • The scan.nextLine(); apparently needs to be after the first print statement and before the sentence[i] statement in order to read the very first instance as well. Thank you very much! – Anon Feb 02 '19 at 17:54
  • @Anon it will work if you put it at the end of the `for loop` or after the first `System.out.println` statement, just know that you need to consume the new line character after `nextInt()` method call. – Yousaf Feb 02 '19 at 17:57
1

Put scan.nextLine() like this:

for(i = 0; i < n; i++){
    System.out.println("Enter String" + (i + 1) + ":");
    sentence[i] = scan.nextLine();

    System.out.printf("Enter int " + (i + 1) + ":");
    numbers[i] = scan.nextInt();
    scan.nextLine();

}
heyza22
  • 313
  • 1
  • 13