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.

4

2 回答 2

5

只需在count++下面添加guess = keyboard.nextInt();

于 2013-11-10T19:30:35.313 回答
2

只需在 do while 循环中添加一个增量count = count + 1;作为最后一个命令。它可以在 do 循环中的任何地方工作,但在处理输入之后放置它是合乎逻辑的。

System.out.println("Number of guesses:"+count);然后在循环下添加一行。

于 2013-11-10T19:32:18.243 回答