File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

weird hasNextDouble behavior.

 
Pete Clark
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Pete Clark
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cleaner code:
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic