0

So far I have,

package randomnumberguessinggame;
import java.util.Scanner;

public class RandomNumberGuessingGame {

public static void main(String[] args) {
     int secretNumber;
        secretNumber = (int) (Math.random() * 999 + 1);

        Scanner keyboard = new Scanner(System.in);
        int guess;
        int count = 0;
        do {
              System.out.print("Enter a guess: (1-1000) ");
              guess = keyboard.nextInt();
              System.out.println("Your guess is " + guess);
              if (guess == secretNumber)
                    System.out.println("Your guess is correct. Congratulations!");

              else if (guess < secretNumber)
                    System.out.println("Your guess is smaller than the secret number.");

              else if (guess > secretNumber)
                    System.out.println("Your guess is greater than the secret number.");

        } while (guess != secretNumber);                         
    }
}

This code works but I need to know how to count the number of user inputs. Thanks in advance.

1
  • update count as count++ inside while . The number of user inputs would be equals to count-1 when you exit the loop. Commented Nov 10, 2013 at 19:29

2 Answers 2

5

Just add count++ under guess = keyboard.nextInt();

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

Comments

2

Just add one incrementation into your do while loop count = count + 1; as the last command. It would work anywhere in the do loop, but it's logical to put it after the input was processed.

Then add a line System.out.println("Number of guesses:"+count); under your loop.

Comments

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.