亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何計算多次猜測一個數字所需的平均猜測次數

如何計算多次猜測一個數字所需的平均猜測次數

牧羊人nacy 2023-08-23 17:08:28
所以我們在我們的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);      }   }
查看完整描述

1 回答

?
搖曳的薔薇

TA貢獻1793條經驗 獲得超6個贊

我創建了一個猜數字游戲。目標是向您展示如何使用嵌套循環而不是遞歸調用 main 方法。它可能無法滿足您的所有要求。您可以添加很多東西,例如根據難度級別計算平均猜測值。給出提示,確保用戶輸入的數字在難度級別等范圍內......


我已經在評論中解釋了邏輯。


public static void main(String args[]) {

   String playAgain = "yes";

   ArrayList<Integer> totalGuesses = new ArrayList<>(); // Keep track of total guesses in all rounds

   int round = 1; // Round number

   do {

      // Prints greeting

      System.out.println("Welcome to High Low game.\nPlease enter difficulty level.");

      System.out.println("Level 1: Easy Range [1-10]");

      System.out.println("Level 2: Medium Range [1-100]");

      System.out.println("Level 3: Hard Range [1-1000]");

      System.out.print("\nEnter Level Number: ");


      Scanner scanner = new Scanner(System.in);

      int difficultyLevel = scanner.nextInt();

      // Making sure that user inputs difficulty level within a certain range

      while (!(difficultyLevel > 0 && difficultyLevel <= 3)) {

         System.out.print("Please enter correct difficulty level: ");

         difficultyLevel = scanner.nextInt();

      }

      // Displays selected difficulty level

      System.out.println("Difficulty level is set to " + difficultyLevel + "\n");

      int theNumber = 0;


      if (difficultyLevel == 1) { // This part is copied from your code

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

      } else if (difficultyLevel == 2) {

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

      } else if (difficultyLevel == 3) {

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

      }


      boolean hasGuessed = false;

      int numberOfGuesses = 0; // keep track of number of guesses in each round

      int guessedNumber;

      ArrayList<Integer> alreadyGuessed = new ArrayList<>();

      while (!hasGuessed) { // While user has not guessed (This while loop is nested in do while)

         System.out.print("Please guess the number: ");

         guessedNumber = scanner.nextInt();

         if (theNumber == guessedNumber) { // If user guesses correctly

            hasGuessed = true;

            numberOfGuesses++;

            System.out.printf("\nCongratulations you have guessed the number on your number %d attempt",

            numberOfGuesses);

            totalGuesses.add(new Integer(numberOfGuesses));

         } else { // If guess is incorrect

            numberOfGuesses++;

            alreadyGuessed.add(new Integer(guessedNumber));

            if (guessedNumber > theNumber) {

               System.out.println("\nSorry but the number you are trying to guess is lower that your guess");

            } else {

               System.out.println("\nSorry but the number you are trying to guess is higher that your guess");

            }

            // 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

            System.out.println("Already guessed numbers: " + alreadyGuessed.toString());

         }

      }

      // when hasGuessed is true the while loop exits

      System.out.print("\nDo you want to play again? Enter yes or no: ");

      playAgain = scanner.next(); // Asking user if they want another round

      if (playAgain.equalsIgnoreCase("yes")) {

         System.out.println("\nRound " + ++round); //Prints round number plus adds empty line between each round

      }

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

   // If player enters anything besides yes it exits do while loop

   double averageGuesses = calculateAverage(totalGuesses); // Calculates average guesses

   System.out.println("\nYour average number of guesses are " + averageGuesses);

}


/*

 * Adds all elements in array and divides it by arraylist size

 */

private static double calculateAverage(ArrayList<Integer> list) {

   Integer sum = 0;

   if (!list.isEmpty()) {

      // Iterate through list and stores each item in a variable (item)

      for (Integer item : list) { 

         sum += item; // short form of sum = sum + item;

      }

      return sum.doubleValue() / list.size();

   }

   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: 1

Difficulty level is set to 1


Please guess the number: 6


Sorry but the number you are trying to guess is lower that your guess

Already guessed numbers: [6]

Please guess the number: 2


Sorry but the number you are trying to guess is higher that your guess

Already guessed numbers: [6, 2]

Please guess the number: 5


Congratulations you have guessed the number on your number 3 attempt

Do you want to play again? Enter yes or no: yes


Round 2

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: 1

Difficulty level is set to 1


Please guess the number: 1


Congratulations you have guessed the number on your number 1 attempt

Do you want to play again? Enter yes or no: no


Your average number of guesses are 2.0


查看完整回答
反對 回復 2023-08-23
  • 1 回答
  • 0 關注
  • 207 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號