+ 28
{Tips For Java}Scanner Bug
There is an unexpected behavior associated with Scanner. When you read a String followed by an int, everything works just fine. But when you read an int followed by a String, unusual thing happens. System.out.print("What is your age? "); age = in.nextInt(); System.out.print("What is your name? "); name = in.nextLine(); System.out.printf("Hello %s, age %d\n", name, age); Try running this example code. It doesn’t let you input your name, and it immediately displays the output: What is your name? Hello , age 20 To understand what is happening, you have to understand that the Scanner doesn’t see input as multiple lines. See comment on how to solve.
4 ответов
+ 28
To solve this problem, you need an extra nextLine after nextInt.
System.out.print("What is your age? ");
age = in.nextInt();
in.nextLine(); // read the newline
System.out.print("What is your name? ");
name = in.nextLine();
System.out.printf("Hello %s, age %d\n", name, age);
This technique is common when reading int or double values that appear on their own line. First you read the number, and then you read the rest of the line, which is just a newline character.
+ 6
This is new. Thanks!
+ 2
using in.next() instead of in.nextLine also solves the problem, if it's a single word input
+ 1
thanks for your note
it was fantastic😊