+ 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.

2nd Mar 2017, 4:14 PM
Ram chandra Giri
Ram chandra Giri - avatar
4 Réponses
+ 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.
2nd Mar 2017, 4:15 PM
Ram chandra Giri
Ram chandra Giri - avatar
+ 6
This is new. Thanks!
2nd Mar 2017, 4:35 PM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar
+ 2
using in.next() instead of in.nextLine also solves the problem, if it's a single word input
2nd Mar 2017, 6:47 PM
Jishnu Jayarajan
+ 1
thanks for your note it was fantastic😊
6th Mar 2017, 5:09 PM
mustafa
mustafa - avatar