Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable equals constant in Java

Tags:

java

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:");

      }
  }
}
like image 858
user1259984 Avatar asked Mar 21 '26 20:03

user1259984


2 Answers

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:

  • The number of guesses left: start it at the constant, decrement it on each step, and compare with 0
  • The number of guesses you've had: start it at 0, increment it, and compare with the constant
like image 146
Jon Skeet Avatar answered Mar 23 '26 10:03

Jon Skeet


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.

like image 38
Mark Peters Avatar answered Mar 23 '26 09:03

Mark Peters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!