我想寫一個小遊戲,但一直堅持如何提示用戶,如果他們想再次玩以及如何退出循環,如果他們不想再玩。 ..如何退出Java循環? While循環在基本的猜謎遊戲
import java.util.Random;
import java.util.Scanner;
public class Guessinggame {
public static void main(String[] args) {
System.out.println("Welcome to guessing game! \n" + " You must guess a number between 1 and 100. ");
while (true) {
Random randomNumber = new Random();
Scanner g = new Scanner(System.in);
int number = randomNumber.nextInt(100) + 1;
int guess = 0;
int numberOfGuesses = 0;
while (guess != number){
System.out.print("Guess: ");
guess = g.nextInt();
if (guess > number){
System.out.println("You guessed too high!");
}else if (guess < number){
System.out.println("You guessed too low!");
}else{
System.out.println("Correct! You have guessed "+ numberOfGuesses + " times. \nDo you want to play again? (y/n) ");
}
numberOfGuesses++;
}
}
}
}
退出循環的最佳選擇是使用'break'。因此,創建一個條件(如果)並檢查用戶是否想再次播放,如果不是,則返回中斷 – k4sia