Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.4k points)

I am using the Scanner methods nextInt() and nextLine()for reading input.

It looks like this:

System.out.println("Enter numerical value"); int option; option = input.nextInt(); // Read numerical value from input System.out.println("Enter 1st string"); String string1 = input.nextLine(); // Read 1st string (this is skipped) System.out.println("Enter 2nd string"); String string2 = input.nextLine(); // Read 2nd string (this appears right after reading numerical value)

The problem is that after entering the numerical value, the first input.nextLine() is skipped and the second input.nextLine() is executed so that my output looks like this:

Enter numerical value 3 // This is my input Enter 1st string // The program is supposed to stop here and wait for my input, but is skipped Enter 2nd string // ...and this line is executed and waits for my input

I tested my application and it looks like the problem lies in using input.nextInt(). If I delete it, then both string1 = input.nextLine() and string2 = input.nextLine() are executed as I want them to be.

1 Answer

0 votes
by (46k points)

This is happening because of the Scanner.nextInt method does not read the newline character in the input generated by hitting "Enter," and so the call to Scanner.nextLine retorts after reading that newline.

You will face alike behavior when you use Scanner.nextLine after Scanner.next() or any Scanner.nextFoo method (excluding nextLine itself).

You can try to:

Either put a Scanner.nextLine call after various Scanner.nextInt or Scanner.nextFoo to utilize rest of that line including newline

int option = input.nextInt();

input.nextLine();  // Consume newline left-over

String str1 = input.nextLine();

Or, even commendable, read the input by Scanner.nextLine and change the input to the proper format you want. For example, you may change to an integer using Integer.parseInt(String) method.

int option = 0;

try {

    option = Integer.parseInt(input.nextLine());

} catch (NumberFormatException e) {

    e.printStackTrace();

}

String str1 = input.nextLine();

Happy Learning..!!

Related questions

0 votes
1 answer
asked Aug 29, 2019 in Java by Ritik (3.5k points)
0 votes
1 answer
asked Feb 17, 2021 in SQL by dev_sk2311 (45k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...