gpt4 book ai didi

java - 一旦你猜对了数字,如何让这个猜数字游戏重新开始?

转载 作者:行者123 更新时间:2023-12-02 05:10:55 25 4
gpt4 key购买 nike

我不知道如何让游戏自行重新启动。我想我需要在 System.out.println(“好吧,让我们再玩一次。”); 的地方放一些东西。我需要在那里放什么来重新启动它?我错过了什么?

import java.util.Random;
import java.util.Scanner;

public class GuessMyNumber {

public static void main(String[] args) {

Random Bob = new Random();
int NumToGuess = Bob.nextInt(20);
int NumOfTries = 0;
Scanner Bill = new Scanner(System.in);
int guess;
boolean win = false;

while (win == false) {

System.out.println("I'm thinking of a number between 1 and 20, can you guess it?");
guess = Bill.nextInt();
NumOfTries++;

if (guess == NumToGuess) {
win = true;
}
else if (guess < NumToGuess) {
System.out.println("Your guess is too low");
}
else if (guess > NumToGuess) {
System.out.println("Your guess is too high");
}
}

System.out.println("Congratulations!");
System.out.println("The number was " + NumToGuess);
System.out.println("It took you " + NumOfTries + " tries");

while (win == true) {
String YesOrNo;
YesOrNo = Bill.nextLine();
System.out.println("Would you like to play again? " + YesOrNo);
YesOrNo = Bill.nextLine();

if (YesOrNo.equalsIgnoreCase("yes"))
{
System.out.println("Ok, let's play again.");
}
else
{
System.out.println("Ok, maybe next time.");
}
}
}
}

最佳答案

你也可以尝试这样的事情:

public class MainClass {

public static void main(String[] args) {
Random bob = new Random();
Scanner bill = new Scanner(System.in);

String yesOrNo = "";
do {

int numToGuess = bob.nextInt(20);
int numOfTries = 0;
int guess = 0;
boolean win = false;

while (win == false) {

System.out
.println("I'm thinking of a number between 1 and 20, can you guess it?");
guess = Bill.nextInt();
numOfTries++;

if (guess == numToGuess) {
win = true;
} else if (guess < numToGuess) {
System.out.println("Your guess is too low");
} else if (guess > numToGuess) {
System.out.println("Your guess is too high");
}
}

System.out.println("Congratulations!");
System.out.println("The number was " + NumToGuess);
System.out.println("It took you " + NumOfTries + " tries");

yesOrNo = bill.nextLine();
System.out.println("Would you like to play again? " + yesOrNo);
yesOrNo = bill.nextLine();

} while (yesOrNo.equalsIgnoreCase("yes"));

System.out.println("Ok, maybe next time.");
System.exit(0);

}

}

关于java - 一旦你猜对了数字,如何让这个猜数字游戏重新开始?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27348175/

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