PDA

View Full Version : cheking to see if input is double


daniel_g
12-01-2006, 02:49 AM
Sorry for asking this simple question, but I've got a bad cold today, and can't think properly. I probably even have an example on how to solve that problem somewhere on my computer, but I can't keep staring at the monitor any longer.


I'm trying to check the user's input is a double or not. So far this is what I've got:

while(bool == 0){
try{
System.out.println("Enter Rate of Fire: ");
CSrate = scan.nextDouble();
bool = 1;
}
catch(Exception e){
System.out.println("Not a number");
}//end catch
}//end while

If I run it one time, and hit, for example, "k" instead of a double, the program will just loop forever asking for the rate of fire, and telling me is "not a number" without allowing user to input the rate of fire again. Maybe try - catch inside a while loop doesn't quite work the way I'm hoping it does.

I'm going to go rest for a couple hours, and hopefully I'll have a reply by the time I wake up, or maybe my mind will be clrear enough to figure it out my self.

Aradon
12-01-2006, 05:08 AM
Eh, don't worry about it. This is a problem that a lot of beginning programmers run into (not that I'm saying you are one) so it will be a good topic to search on.

The reason that it doesn't work is because when an exception is thrown the token that is currently in the scanner is never consumed. So as far as the scanner is concerned it will always be stuck on that string.

So how do you fix it? Well you have to consume the token of course!

Just add


scan.nextLine();


To your exception so it looks like..


while(bool == 0){
try{
System.out.println("Enter Rate of Fire: ");
CSrate = scan.nextDouble();
bool = 1;
}
catch(Exception e){
System.out.println("Not a number");
scan.nextLine();
}//end catch


And it will work fine. At the least, it works on mine!

(btw, there is a way to do it without the exception handling by using the method hasNextDouble() )

Hope that helps and get well soon. I like nyquil when I'm sick ;)

daniel_g
12-01-2006, 07:53 AM
Thank you.

OK, so in english, when you say consume the token, you mean move to a new line?
I am a beginner :p

btw, there is a way to do it without the exception handling by using the method hasNextDouble()
Yeah, that's the one I learned last semester, and I know I have one or two programs using it, but was feeling way to bad to look for them. But I'm sticking with the exception way, since it's working now.

I don't think they sell nyquil arround here(maybe it's behind the counter). All I see at CVS is tylenol everywhere.

Aradon
12-01-2006, 06:58 PM
NyQuil Behind the counter?! That sounds like product racism!

<3 my NyQuil