所以我为数字猜谜游戏写了一个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 = ");
}
}
答案 0 :(得分:0)
跟踪最佳分数,即最低猜测次数。
int bestGame = Integer.MAX_VALUE; // at the top
bestGame = Math.min(bestGame, numberOfTries); // at the end of your inner while loop
最差的分数是最高猜测次数,受Integer.MAX_VALUE限制,所以你从那里开始。
答案 1 :(得分:0)
要符合您已编写的代码,您可以
int bestGame = Integer.MAX_VALUE;
。numberOfGuesses
是否小于当前bestGame
,如果是,请用当前{{覆盖bestGame
1}}。 numberOfGuesses
。答案 2 :(得分:0)
为了获得最好的游戏,您需要在每场比赛后跟踪最好的游戏,例如检查它的变量,每场比赛后都有一个新的最佳游戏。
答案 3 :(得分:0)
通过最好的游戏,你的意思是最小的尝试次数是最好的游戏。
/* int mintries,bestgame,gamenumber=0;
bestgamenumber=0;mintreies=Integer.MAX_VALUE:*/
在上面(播放)
上方添加上面的行 gamenumber++;
/*if(mintries>numberOfTries)
{
mintries=numberOfTries;//update mintries
betgame=gamenumber;
}*/
在关闭之前添加if条件(play)。 所以它就像
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)是最好的,最小的尝试是猜测最好的游戏。如果我错了,请更正我。