wood burning stoves 2.0
The moose likes Beginning Java and the fly likes need help with endless loop when dealing with Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "need help with endless loop when dealing with "if (keyboard.hasNextDouble())"" Watch "need help with endless loop when dealing with "if (keyboard.hasNextDouble())"" New topic

need help with endless loop when dealing with "if (keyboard.hasNextDouble())"

Holden Hodgdon

Joined: May 24, 2011
Posts: 4
ok, this is for my Java class and the task in question is right out of the text book.

the goal is to write up a calculator that spits out the projected height of a kid based on the supplied gender and the heights of the two parents.

I got the actual calculations working but now I'm dealing with how to make an error code loop when dealing with a double but the user entered a string.

here is the problem child:

now I actually ended up using another method to get this done with "try" and "catch" but using the "if (keyboard.hasNextDouble())" method seems so much simplistic if only I could get the thing to stop going into an endless loop if someone types in "dog".

is there some way to get this thing to not flip out? I have a hard time swallowing that there isn't some simple command to jump back up to the start of the loop.

if anyone wants to play with it here is the complete brick of code, even though this is for homework I don't mind spitting it out because gates A & B aren't fully working.

Rob Spoor

Joined: Oct 27, 2005
Posts: 20274

Welcome to the Ranch!

This is actually an often made mistake with Scanner. If keyboard.hasNextDouble() returns false but keyboard.hasNext() returns true, there is something available that is not a double. Because your loop keeps checking only for double but that something remains the first thing inside the scanner. The solution is very simple: consume that something:

How To Ask Questions How To Answer Questions
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46362
Welcome to the Ranch

I am afraid I have a few comments about your code. You haven't indented it the usual way, and your lines are so long they are difficult to read. When I tried to correct the long lines, it didn't look much better; that is because you are using tabs. Have a look here to see why tabs aren't a good idea.

Also you have written == true or != true or something. Never never write that sort of thing. Not only is it poor style, but also error-prone; you can easily write = instead of ==. If you want something false, use the bang operator, like this if (!foo.isTrue()) ...
I agree. Here's the link: http://aspose.com/file-tools
subject: need help with endless loop when dealing with "if (keyboard.hasNextDouble())"
It's not a secret anymore!