如何将简单游戏的尝试限制为仅三次?我认为你会使用布尔值。但不确定。
import java.util.Scanner;
public class guess {
public static void main(String[] args) {
int randomN = (int) (Math.random() * 10) + 1;
Scanner input = new Scanner(System.in);
int guess;
System.out.println("Enter a number between 1 and 10.");
System.out.println();
do {
System.out.print("Enter your guess: ");
guess = input.nextInt();
if (guess == randomN) {
System.out.println("You won!");
} else if (guess > randomN) {
System.out.println("Too high");
} else if (guess < randomN) {
System.out.println("Too low");
}
} while (guess != randomN);
}
}
答案 0 :(得分:1)
#ifdef _MSC_VER
// Map to equivalent function
#define snprintf sprintf_s
#endif
答案 1 :(得分:0)
使用旗帜。将其初始化为0.如果猜测正确,则将其重置为0.如果不增加1.在每次猜测之前,检查标志是否>如果没有让继续,如果是的话。
答案 2 :(得分:-1)
您可以在猜测失败期间递增。我相信变量应该位于循环之外。然后剩下的就是添加一个部分,在猜测用完时通知用户失败。
public static void main(String[]args) {
int rNumber = (int)(Math.random() * 10) + 1;
Scanner input = new Scanner(System.in);
int guess;
int tries = 0;
int success = 0;
System.out.println("Enter a number between 1 and 10.");
System.out.println();
do {
System.out.println("Enter your guess: ");
guess = input.nextInt();
if(guess == rNumber) {
System.out.println("You guessed right! You win!");
success++;
} else if (guess < rNumber) {
System.out.println("Too low");
tries++;
} else if (guess > rNumber) {
System.out.println("Too high.");
tries++;
}
} while(tries != 3 && success != 1 || success != 1);
}