如何计算多次猜测一个数字所需的平均猜测次数

所以我们在我们的java类中制作HiLo,并且说明说玩家应该能够玩多次。所以我已经这样做了,并且还计算了猜测所有游戏数量所需的平均猜测次数,我不知道如何做到这一点,因为猜测数量在游戏重置后重置?


我对时间有同样的问题(完全相同的事情,猜测数字所需的平均时间)


我尝试过编写猜测++,但我不知道如何“存储”每个游戏所需的猜测次数,也不知道如何做到这一点


public class HiLo{


   //Globala-Variabler

   static int tal = 0;

   static int totaltSpelade = 0;

   static int gissning = 1;

   static int antalGissningar = 0;



   public static void main(String args[]) throws InterruptedException {

      // val slingan



      int val = Kbd.readInt("\nKlicka 1 för 1-10\nKlicka 2 för 1-100\nKlicka 3 för 1-1000");



      if (val == 1){

         tal = (int) (Math.random() * 10)+1;

      }



      else if (val == 2){

         tal = (int) (Math.random() * 100)+1;

      }



      else if (val ==3){

         tal = (int) (Math.random() * 1000)+1;

      }

      else{

         Kbd.clearScreen();

         System.out.println("\nFelinmatning!");

         main(null);

      }



      // tid och gissnings slinga

      int gissningar = Kbd.readInt("\nBörja gissa!");

      long startTid = System.currentTimeMillis();



      slinga();



      //stop tid

      System.out.println("\nGrattis!\nDu gissade rätt tal på " + antalGissningar + " försök!");

      long stopTid = System.currentTimeMillis();

      long tid = stopTid-startTid;

      System.out.print("Det tog dig! " + (tid/1000) + "s");

      totaltSpelade++;



      int avsluta = Kbd.readInt("\nKlicka 1 för att köra igen\nKlicka 2 för att avsluta");

      if (avsluta == 1){

         //Kbd.clearScreen();

         main(null);

      }



      else{

         System.out.println("\nHejdå!, Det tog dig i snitt " +

         // THIS IS WHERE I WANT TO PRINT OUT THE AVERAGE NUMBER OF GUESSES OF ALL GAMES

         (antalGissningar/totaltSpelade) + " gissningar per gång.");


         System.out.println("\nOch i snitt " + (tid/1000) + " s");

         //Kbd.clearScreen();

         System.exit(0);

      }

   }




牧羊人nacy
浏览 108回答 1
1回答

摇曳的蔷薇

我创建了一个猜数字游戏。目标是向您展示如何使用嵌套循环而不是递归调用 main 方法。它可能无法满足您的所有要求。您可以添加很多东西,例如根据难度级别计算平均猜测值。给出提示,确保用户输入的数字在难度级别等范围内......我已经在评论中解释了逻辑。public static void main(String args[]) {&nbsp; &nbsp;String playAgain = "yes";&nbsp; &nbsp;ArrayList<Integer> totalGuesses = new ArrayList<>(); // Keep track of total guesses in all rounds&nbsp; &nbsp;int round = 1; // Round number&nbsp; &nbsp;do {&nbsp; &nbsp; &nbsp; // Prints greeting&nbsp; &nbsp; &nbsp; System.out.println("Welcome to High Low game.\nPlease enter difficulty level.");&nbsp; &nbsp; &nbsp; System.out.println("Level 1: Easy Range [1-10]");&nbsp; &nbsp; &nbsp; System.out.println("Level 2: Medium Range [1-100]");&nbsp; &nbsp; &nbsp; System.out.println("Level 3: Hard Range [1-1000]");&nbsp; &nbsp; &nbsp; System.out.print("\nEnter Level Number: ");&nbsp; &nbsp; &nbsp; Scanner scanner = new Scanner(System.in);&nbsp; &nbsp; &nbsp; int difficultyLevel = scanner.nextInt();&nbsp; &nbsp; &nbsp; // Making sure that user inputs difficulty level within a certain range&nbsp; &nbsp; &nbsp; while (!(difficultyLevel > 0 && difficultyLevel <= 3)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.print("Please enter correct difficulty level: ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;difficultyLevel = scanner.nextInt();&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; // Displays selected difficulty level&nbsp; &nbsp; &nbsp; System.out.println("Difficulty level is set to " + difficultyLevel + "\n");&nbsp; &nbsp; &nbsp; int theNumber = 0;&nbsp; &nbsp; &nbsp; if (difficultyLevel == 1) { // This part is copied from your code&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;theNumber = (int) (Math.random() * 10) + 1;&nbsp; &nbsp; &nbsp; } else if (difficultyLevel == 2) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;theNumber = (int) (Math.random() * 100) + 1;&nbsp; &nbsp; &nbsp; } else if (difficultyLevel == 3) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;theNumber = (int) (Math.random() * 1000) + 1;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; boolean hasGuessed = false;&nbsp; &nbsp; &nbsp; int numberOfGuesses = 0; // keep track of number of guesses in each round&nbsp; &nbsp; &nbsp; int guessedNumber;&nbsp; &nbsp; &nbsp; ArrayList<Integer> alreadyGuessed = new ArrayList<>();&nbsp; &nbsp; &nbsp; while (!hasGuessed) { // While user has not guessed (This while loop is nested in do while)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.print("Please guess the number: ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;guessedNumber = scanner.nextInt();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (theNumber == guessedNumber) { // If user guesses correctly&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; hasGuessed = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; numberOfGuesses++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.printf("\nCongratulations you have guessed the number on your number %d attempt",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; numberOfGuesses);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; totalGuesses.add(new Integer(numberOfGuesses));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} else { // If guess is incorrect&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; numberOfGuesses++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alreadyGuessed.add(new Integer(guessedNumber));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (guessedNumber > theNumber) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("\nSorry but the number you are trying to guess is lower that your guess");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("\nSorry but the number you are trying to guess is higher that your guess");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Prints already guessed so user doesn't enter same value. You can program so it doesn't accept same number by checking the guessedNumber againstalreadyGuessed&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Already guessed numbers: " + alreadyGuessed.toString());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; // when hasGuessed is true the while loop exits&nbsp; &nbsp; &nbsp; System.out.print("\nDo you want to play again? Enter yes or no: ");&nbsp; &nbsp; &nbsp; playAgain = scanner.next(); // Asking user if they want another round&nbsp; &nbsp; &nbsp; if (playAgain.equalsIgnoreCase("yes")) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("\nRound " + ++round); //Prints round number plus adds empty line between each round&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;} while (playAgain.equalsIgnoreCase("yes"));&nbsp; &nbsp;// If player enters anything besides yes it exits do while loop&nbsp; &nbsp;double averageGuesses = calculateAverage(totalGuesses); // Calculates average guesses&nbsp; &nbsp;System.out.println("\nYour average number of guesses are " + averageGuesses);}/*&nbsp;* Adds all elements in array and divides it by arraylist size&nbsp;*/private static double calculateAverage(ArrayList<Integer> list) {&nbsp; &nbsp;Integer sum = 0;&nbsp; &nbsp;if (!list.isEmpty()) {&nbsp; &nbsp; &nbsp; // Iterate through list and stores each item in a variable (item)&nbsp; &nbsp; &nbsp; for (Integer item : list) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;sum += item; // short form of sum = sum + item;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; return sum.doubleValue() / list.size();&nbsp; &nbsp;}&nbsp; &nbsp;return sum;}示例输出:Welcome to High Low game.Please enter difficulty level.Level 1: Easy Range [1-10]Level 2: Medium Range [1-100]Level 3: Hard Range [1-1000]Enter Level Number: 1Difficulty level is set to 1Please guess the number: 6Sorry but the number you are trying to guess is lower that your guessAlready guessed numbers: [6]Please guess the number: 2Sorry but the number you are trying to guess is higher that your guessAlready guessed numbers: [6, 2]Please guess the number: 5Congratulations you have guessed the number on your number 3 attemptDo you want to play again? Enter yes or no: yesRound 2Welcome to High Low game.Please enter difficulty level.Level 1: Easy Range [1-10]Level 2: Medium Range [1-100]Level 3: Hard Range [1-1000]Enter Level Number: 1Difficulty level is set to 1Please guess the number: 1Congratulations you have guessed the number on your number 1 attemptDo you want to play again? Enter yes or no: noYour average number of guesses are 2.0
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java