所以我为一个猜数字游戏写了一个java代码。整个事情几乎完成了。它的工作原理是选择一个随机数,然后要求用户输入控制台输入,然后说出该输入是高于还是低于随机数。一旦你猜到了,它就会询问你是否要再玩一次。当你最终对此说不时(无论是一场比赛还是几场比赛),它会打印出您的总体结果,包括总游戏数、总猜测数、平均猜测数/游戏和最佳游戏。我已经解决了所有问题,除了我不知道如何让它打印出您的整体最佳游戏。
import java.util.*; //so I can use scanner
public class GuessingGame {
public static void main(String[] args) {
Random rand = new Random ();
int max = 100;
Scanner input = new Scanner(System.in);
int guess;
boolean play = true;
int totalGames = 0;
int totalGuesses = 0;
System.out.println("Can you guess the word?");
System.out.println("I am sure you cannot guess!");
System.out.println("Go ahead and try!");
System.out.println();
while (play) {
System.out.println("I'm thinking of a number between 1 and " + max + "...");
int numberToGuess = rand.nextInt(max) + 1;
int numberOfTries = 0;
boolean win = false;
while (!win) {
System.out.print("Your guess? ");
guess = input.nextInt();
numberOfTries++;
if (guess == numberToGuess) {
win = true;
} else if (guess > numberToGuess) {
System.out.println("It's lower.");
} else if (guess < numberToGuess) {
System.out.println("It's higher.");
}
input.nextLine();
}
if (numberOfTries == 1) {
System.out.println("You got it right in " + numberOfTries + " guess!");
} else {
System.out.println("You got it right in " + numberOfTries + " guesses!");
}
totalGames++;
totalGuesses+= numberOfTries;
System.out.print("Do you want to play again? ");
String answer = input.nextLine();
char firstLetter = answer.charAt(0);
if (firstLetter == 'y' || firstLetter == 'Y') {
play = true;
} else {
play = false;
}
System.out.println();
}
System.out.println("Overall results:");
System.out.println("Total games = " + totalGames);
System.out.println("Total guesses = " + totalGuesses);
System.out.println("Guesses/game = " + totalGuesses/totalGames);
System.out.println("Best game = ");
}
}
为了获得最好的游戏,你需要在每场比赛后跟踪最好的游戏,比如一个变量来检查每场比赛后是否有一个新的最佳游戏。
跟踪最佳分数,这是最少的猜测次数。
int bestGame = Integer.MAX_VALUE; // at the top
bestGame = Math.min(bestGame, numberOfTries); // at the end of your inner while loop
最差的分数是猜测次数最多,受 Integer.MAX_VALUE 的限制,因此您从那里开始。
最好的游戏 u 意味着回答所需的最小尝试次数是最好的游戏。
/* int mintries,bestgame,gamenumber=0;
bestgamenumber=0;mintreies=Integer.MAX_VALUE:*/
在 while(播放)上方添加上述行
gamenumber++;
/*if(mintries>numberOfTries)
{
mintries=numberOfTries;//update mintries
betgame=gamenumber;
}*/
在关闭时(播放)之前添加 if 条件。 所以它会像
int mintries;
mintreies=Integer.MAX_VALUE:
int gamenumber=0;
int bestgamenumber=0//if you want to print the which game is the best game(!st,2nd,3rd..) ;
while(play)
{
// do all your stuff
gamenumber++;
if(mintries>numberOfTries)
{
mintries=numberOfTries;//update mintries
bestgamenumber=gamenumber;
}
}
}
System.out.println("Game number +bestgamenumber+"was the best game with"+ mintries+"tries);
我正在考虑您要打印哪个游戏(1st,2nd,3rd)是最好的,并且尝试猜测最佳游戏的次数最少。如果我错了,请纠正我。
为了适应你已经编写的代码,你可以
- 创建一个新的"全局"变量,例如
int bestGame = Integer.MAX_VALUE;
。 - 每当用户完成游戏时,请检查当前
numberOfGuesses
是否小于当前bestGame
,如果是,则用当前numberOfGuesses
覆盖bestGame
。 - 最后,您只需要输出
bestGame
.