我试图制作一个用户有3次机会猜测程序生成的随机数的游戏。到目前为止我有这个代码,但我不知道如何在用户输入3个猜测中的3个后停止程序。如果用户无法在3次尝试中正确猜测,我希望程序说"你松了。这个数字是......"
import java.util.Random;
import java.util.Scanner;
class GuessNumber {
public static void main(String args[]) {
Random random = new Random();
Scanner input = new Scanner(System.in);
int MIN = 1;
int MAX = 10;
int comp = random.nextInt(MAX - MIN + 1) + MIN;
int user;
do {
System.out.print("Guess a number between 1 and 10: ");
user = input.nextInt();
if (user > comp)
System.out.println("My number is less than " + user + ".");
else if (user < comp)
System.out.println("My number is greater than " + user + ".");
else
System.out.println("Correct! " + comp + " was my number! " );
} while (user != comp);
}
}
答案 0 :(得分:0)
只需计算尝试次数,并在达到阈值后退出循环。像那样:
int attemptsNum = 0;
final int maxAttempts = 3;
do {
System.out.print("Guess a number between 1 and 10: ");
user = input.nextInt();
if (user > comp)
System.out.println("My number is less than " + user + ".");
else if (user < comp)
System.out.println("My number is greater than " + user + ".");
else
System.out.println("Correct! " + comp + " was my number! ");
} while (user != comp && ++attemptsNum <maxAttempts );
if (attemptsNum == maxAttempts)
System.out.println("You loose. The number was :" + comp);