SI 为猜数字游戏编写了 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 的限制,所以你从那里开始。
最佳游戏是指需要尝试最少次数才能回答的游戏。
/* int mintries,bestgame,gamenumber=0;
bestgamenumber=0;mintreies=Integer.MAX_VALUE:*/
将上述行添加到 while(play) 上方
gamenumber++;
/*if(mintries>numberOfTries)
{
mintries=numberOfTries;//update mintries
betgame=gamenumber;
}*/
在关闭 while(play) 之前添加 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);
我正在考虑你想打印哪个游戏(第1、第2、第3)最好,并进行最少的尝试来猜测最好的游戏。如果我错了,请纠正我。
为了适应您已经编写的代码,您可以
int bestGame = Integer.MAX_VALUE;
。numberOfGuesses
是否小于当前 bestGame
,如果是,则用当前 bestGame
覆盖 numberOfGuesses
。 bestGame
即可。