Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Holden Hodgdon
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Pie
Posts: 20550
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Campbell Ritchie
Sheriff
Pie
Posts: 49411
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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()) ...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic