Colin
Colin

Reputation: 33

Count number of user inputs

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

Upvotes: 3

Views: 22353

Answers (3)

vijay
vijay

Reputation: 2694

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

Upvotes: 1

PermGenError
PermGenError

Reputation: 46408

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
        }

Upvotes: 2

Dylan
Dylan

Reputation: 13914

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++

Upvotes: 3

Related Questions