gpt4 book ai didi

java - 如何退出Java循环?基本猜谜游戏中的 while 循环

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:43:37 25 4
gpt4 key购买 nike

我正在尝试编写一个小游戏,但一直停留在如何提示用户是否想再次玩以及如何退出循环如果他们不想再次玩......

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 来跳出当前循环。

for (int i = 0; i < 10; i++) {
if (i > 5) {
break;
}
System.out.Println(i);
}

打印:

0
1
2
3
4
5

但是,一个 do-while loop 可能更适合您的用例。

关于java - 如何退出Java循环?基本猜谜游戏中的 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20099928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com