到目前为止,我有,
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);
}
}
此代码有效,但我需要知道如何计算用户输入的数量。 提前谢谢。
答案 0 :(得分:5)
只需在count++
guess = keyboard.nextInt();
即可
答案 1 :(得分:2)
只需在do while循环count = count + 1;
中添加一个增量作为最后一个命令。它可以在do循环中的任何地方工作,但在处理输入之后将其放入是合乎逻辑的。
然后在你的循环下添加一行System.out.println("Number of guesses:"+count);
。