I'm building a guessing game with Strings. The concept is pretty simple. I have a limited number of tries defined by a Java constant(C_Max_Trials = 10) and when the number of guesses reaches this constant the app should exit. The only thing is that I have to use this constant, this being part of my university assignment.
My problem is that Java won't consider my statements:
if (nrOfGuesses == C_Max_Trials) {
System.out.println("Sorry you are out of tries");
System.exit(0);"
If I put
nrOfGuesses == 0
it will work just fine. If I let
nrOfGuesses == C_Max_Trials
then it will not stop at 10 guesses and it will move on to guesses no -1,-2,-3.... continuing with the loop.
I'm attaching my code below. Also if you have any other feedback regarding the code it would be appreciated. I'm just starting with coding.
Thanks !
My code is:
public class Assignment4 {
public static final int C_Max_Trials = 10;
//Start Game
String correctName = "X";
boolean finished = false;
int nrOfGuesses=10;
while (!finished) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please guess the name: ");
String name = keyboard.nextLine();
if (name.equals(correctName))
{
finished = true;
System.out.println("Congratulations! You have guessed the name in "
+ nrOfGuesses+ " tries!");
System.exit(0);
}
--nrOfGuesses;
if (nrOfGuesses == C_Max_Trials) {
System.out.println("Sorry you are out of tries");
System.exit(0);
}
System.out.println("Sorry, you haven't guessed the name. You have "+
nrOfGuesses + " left. Please try again:");
}
}
}
If nrOfGuesses starts at 10 and then only gets decremented... how do you expected it to be equal to 10? (Barring overflow...)
You need to decide whether nrOfGuesses is meant to be:
You're counting down (--nrOfGuesses) from 10.
Count up (nrOfGuesses++) from 0 to C_Max_Trials or count down from C_Max_Trials instead of the hardcoded 10.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With