3

I searched for my query but couldn't find anything of use. I'm just starting to learn Java and I made a basic guessing game program. My problem is that I need to count the number of guesses the user makes and I'm unsure how to do this. I would really appreciate any help you guys could give me. Here is my code so far:

double ran;
ran = Math.random();
int r = (int)(ran*100);

Scanner in = new Scanner (System.in);
int g = 0;

System.out.print("Please make a guess between 1 and 100: ");
g = in.nextInt();

while (g!=r){

  if (g<=0){
    System.out.print("Game over.");
    System.exit(0); 
  }

  else if (g>r){
    System.out.print("Too high. Please guess again: ");
    g = in.nextInt();
  }

  else if (g<r){
    System.out.print("Too low. Please guess again: ");
    g = in.nextInt();                               
  }
}

System.out.print("Correct!");

3 Answers 3

3

You'll want a variable to keep track of your guess count. Declare it somewhere that will only get run once per game, a la

int guessCount = 0

And then, within your guess loop, increment guessCount.

guessCount++
Sign up to request clarification or add additional context in comments.

Comments

2

have a count variable and increment it inside the while on every iteration.

    int count=0;
     while(g!=r) {

        count++;
        //rest of your logic goes here
        }

Comments

1

So you would want to maintain a counter, i.e. a variable that will keep count of the number of guesses, and you will want to increment the count by one each time you ask the user to make a guess. So basically, you should be incrementing the counter each time you invoke g = in.nextInt();

So here is what your code should probably be doing...

double ran;
ran = Math.random();
int r = (int)(ran*100);
Scanner in = new Scanner (System.in);
int g = 0;
System.out.print("Please make a guess between 1 and 100: ");
int counter = 0;
g = in.nextInt();
counter++;
while (g!=r) {
    if (g<=0) {
        System.out.print("Game over.");
        System.exit(0);
    }
    else if (g>r) {
        System.out.print("Too high. Please guess again: ");
        g = in.nextInt();
        counter++;
    }
    else if (g<r) {
        System.out.print("Too low. Please guess again: ");
        g = in.nextInt();
        counter++;
    }
}
System.out.print("Correct!");

1 Comment

Thanks for taking the time to add it to my code. Very helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.