我在下面的代碼中的目標是不斷猜測,直到用戶猜測到正確的數字或退出。要退出,我可以很容易地打破我的循環,但是當我嘗試繼續循環時,它無法正常工作。首先它需要多個輸入,然後也完全重新生成我的號碼,而我想要做的是不斷猜測(詢問用戶)相同的隨機數。 下面是我的代碼:無法通過while循環成功重新循環
public class Test {
public static void main(String[] args) {
int count, randNum, guess;
count = 0;
Scanner scan = new Scanner(System.in);
while (true) {
Random rand = new Random();
randNum = rand.nextInt(100) + 1;
System.out.println("Guess a number b/w 1 and 100");
guess = scan.nextInt();
count += 1;
if (guess == randNum) {
System.out.println("Correct guess.");
System.out.println("It took " + count + " tries to guess the right number");
System.out.println("Would you like to play again? ");
System.out.println("Press any letter to play again or q to quit: ");
if (scan.next().charAt(0) == 'q' || scan.next().charAt(0) == 'Q') {
break;
}
else{
continue;
}
}
if (guess > randNum) {
System.out.println("Your guess is bigger than actual number. Would you like to try again?");
System.out.println("Press q to quit or any other letter to try again");
if (scan.next().charAt(0) == 'q' || scan.next().charAt(0) == 'Q') {
break;
}
else {
continue;
}
}
else if (guess < randNum) {
System.out.println("Your guess is smaller than actual number. Would you like to try again?");
System.out.println("Press q to quit or any other letter to try again");
if (scan.next().charAt(0) == 'q' || scan.next().charAt(0) == 'Q') {
break;
}
else {
continue;
}
}
}
}
}
談論一個移動的目標 - randNum正在對環路 –
您需要的遊戲和嘗試分成外部/內部循環的每一次迭代中重新設置。 – shmosel