File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "weird hasNextDouble behavior." Watch "weird hasNextDouble behavior." New topic
Author

weird hasNextDouble behavior.

Pete Clark
Greenhorn

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)
{
System.out.print(prompt);
if (sc.hasNextDouble())
{
d = sc.nextDouble();
isValid = true;
}
else
{
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?

Thanks,

Pete
marc weber
Sheriff

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
sscce.org
Pete Clark
Greenhorn

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!

Pete
Matt Qua
Greenhorn

Joined: Oct 19, 2011
Posts: 1
Cleaner code:
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: weird hasNextDouble behavior.
 
Similar Threads
New to Java - i need help please!
pulling my hair out
my last question for this program.
Forcing Input With The Scanner Class
Class and Object Problem