I am writing a guessing game (just to learn java, no other purpose )
It create's a random number that must be guessed by the user.
Then it asks for user input.
If the number is in the correct range but not the exact number it says if the randomnumber is bigger or smaller.
If the number is correct they get a congratulation message.
The problem is in the error handling. I used a (NumberFormatException nFE) on the parseint to make sure its a real integer.
This works. The problem is that when there is a mistake made the program gives the congratulations message and afterwards sais the number is bigger and asks for a new guess. (entering correct number gives congratulation message and closes the program).
Any idea where my mistake is?
1. Don't recursively call the vraagEnTestNummer() method. That is, don't call vraagEnTestNummer() from within vraagEnTestNummer().
2. You catch NumberFormatException but then call vraagEnTestNummer(). So after it returns from vraagEnTestNummer(), it will continue processing as if the user guessed the number 0. Change the NumberFormatException code to inform the user of the mistake and prompt for input again (See suggestion 3)
3. Rather than recursively calling vraagEnTestNummer(), use a while loop. The first thing in the while loop prompts the user for a number. The while loop terminates when the user has correctly guessed the number.
You might want to consider doing the whole program in a loop rather than recursively.
Suhrid Karthik wrote:Yes the logic is better implemented in a while loop instead of recursion. However, in the recursive method itself, you could terminate the program by calling System.exit() when the user guesses the correct number instead of allowing the method to return.
Also true. It would solve the problem i had.
I like the while loop better because the code looks somewhat clearer to me. I am wandering why I never thought of it in the first place.
Is there a "common practice" or a "best way" to do this?
Since you are probably using Java6, have you tried the Scanner class.
Just a question on the last bit of code Jarco posted(I hope this isn't considered Hijacking!)Does that code snippet work?
is it normal to have 3 "if statements" in a row and then 3"else statements" in a row? I am new so maybe this is something i have just never seen ??
or does that maybe only work with the "Dutch" JVM ;)
It is an experimental device that will make my mind that most powerful force on earth! More powerful than this tiny ad!
The WEB SERVICES and JAX-RS Coursehttps://coderanch.com/t/690789/WEB-SERVICES-JAX-RS