Meaningless Drivel is fun!
The moose likes Beginning Java and the fly likes weird hasNextDouble behavior. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "weird hasNextDouble behavior." Watch "weird hasNextDouble behavior." New topic

weird hasNextDouble behavior.

Pete Clark

Joined: Feb 19, 2006
Posts: 2
I'm trudging through Murach's book and here's the code I have to validate user input in a double:

public static double getDouble(Scanner sc, String prompt)
double d = 0.0;
boolean isValid = false;
while (isValid == false)
if (sc.hasNextDouble())
d = sc.nextDouble();
isValid = true;
System.out.println("Error! Invalid decimal value. Try again.");
sc.nextLine(); // discard any other data entered on the line
return d;

It's a generic method and works fine in several other programs. While testing my current code, I enter "w" and press enter. Here's the result:

Enter customer type (r/c/t): r
Enter subtotal: w
Error! Invalid decimal value. Try again.
Enter subtotal: Error! Invalid decimal value. Try again.
Enter subtotal:

It looks like the sc.nextLine() method is reading the <Enter> after the "w" as a separate command and generating another error message. Should not sc.nextLine flush the buffer and wait for another entry? This came method works great in my other apps.

Any ideas?


marc weber

Joined: Aug 31, 2004
Posts: 11343

Hi Pete, welcome to JavaRanch!

I tried your code, and it works fine for me.

The closest I could get to duplicating your output was by hitting the Enter key before the 'w' and then again afterwards, but this puts the 'w' on a separate line.

My completed code is below...

[ February 23, 2006: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Pete Clark

Joined: Feb 19, 2006
Posts: 2
Thanks for taking a look at it. It's really weird. Works in several other prgrams without a hitch, just not this one. Great forum!

Matt Qua

Joined: Oct 19, 2011
Posts: 1
Cleaner code:
I agree. Here's the link:
subject: weird hasNextDouble behavior.
jQuery in Action, 3rd edition