【问题标题】:Dice Roll Histogram with Loops带循环的掷骰子直方图
【发布时间】:2016-11-30 20:53:15
【问题描述】:

我在课堂上遇到了一个我无法解决的问题。

这是问题:

本测验的目的是加强对使用循环和计数的理解,以及复习随机数的使用。

修改下面的程序以打印一个直方图,其中骰子滚动的总次数等于每个可能的值,通过打印类似 # 的字符来显示该次数。每卷将使用两个骰子。

例子:

直方图显示每个可能值的掷骰总数。

掷骰子统计(结果不同):

2s:######

3s:####

4s:###

5s:########

6s:###################

7s:#############

8s:#############

9s:###############

10 秒:###########

11 秒:#####

12 秒:####

~~~~~~~~~~~~~~~~~~~~~

我无法让程序打印上例中的直方图。

这就是我目前所拥有的:

    import java.util.Scanner;

    import java.util.Random;

    public class DiceStats {

       public static void main(String[] args) {

          Scanner scnr = new Scanner(System.in);

          Random randGen = new Random();

          int seedVal = 11;

          randGen.setSeed(seedVal);

          // FIXME 1 and 2: Set the seed to the Random number generator


          int i = 0;          // Loop counter iterates numRolls times
          int numRolls = 0;   // User defined number of rolls 


          // FIXME 3: Declare and initiate cariables needed

          int numOnes = 0;
          int numTwos = 0;
          int numThrees = 0;
          int numFours = 0;
          int numFives = 0;
          int numSixes = 0;   // Tracks number of 6s found
          int numSevens = 0;  // Tracks number of 7s found
          int numEights = 0;
          int numNines = 0;
          int numTens = 0;
          int numElevens = 0;
          int numTwelves = 0;
          int die1 = 0;       // Dice 1 values
          int die2 = 0;       // Dice 2 values
          int rollTotal = 0;  // Sum of dice values

          System.out.println("Enter number of rolls: ");
          numRolls = scnr.nextInt();

          if (numRolls >= 1) {
             // Roll dice numRoll times
             for (i = 0; i < numRolls; ++i) {
                die1 = randGen.nextInt(6) + 1;
                die2 = randGen.nextInt(6) + 1;
                rollTotal = die1 + die2;

                // FIXME 4: Count number of sixs and sevens; complete the same for all other possible values
                if (rollTotal == 1) {
                   numOnes = numOnes + 1;
                }
                if (rollTotal == 2) {
                   numTwos = numTwos + 1;
                }
                if (rollTotal == 3) {
                   numThrees = numThrees + 1;
                }
                if (rollTotal == 4) {
                   numFours = numFours + 1;
                }
                if (rollTotal == 5) {
                   numFives = numFives + 1;
                }
                if (rollTotal == 6) {
                   numSixes = numSixes + 1;
                }
                if (rollTotal == 7) {
                   numSevens = numSevens + 1;
                }
                if (rollTotal == 8) {
                   numEights = numEights + 1;
                }
                if (rollTotal == 9) {
                   numNines = numNines + 1;
                }
                if (rollTotal == 10) {
                   numTens = numTens + 1;
                }
                if (rollTotal == 11) {
                   numElevens = numElevens + 1;
                }
                else if (rollTotal == 12) {
                   numTwelves = numTwelves + 1;
                }
                System.out.println("Debugging: Roll " + (i+1) + " is " + rollTotal + " (" + die1 + 
              "+" + die2 + ")");
            }

             // Print statistics on dice rolls
             System.out.println("\nDice roll statistics:");

             // FIXME 5: Complete printing the histogram
             System.out.println("1s: " + numOnes);
             System.out.println("2s: " + numTwos);
             System.out.println("3s: " + numThrees);
             System.out.println("4s: " + numFours);
             System.out.println("5s: " + numFives);
             System.out.println("6s: " + numSixes);
             System.out.println("7s: " + numSevens);
             System.out.println("8s: " + numEights);
             System.out.println("9s: " + numNines);
             System.out.println("10s: " + numTens);
             System.out.println("11s: " + numElevens);
             System.out.println("12s: " + numTwelves);
          }
          else {
             System.out.println("Invalid rolls. Try again.");
          }

         return;
       }
    }

任何帮助将不胜感激。

【问题讨论】:

  • 乍一看:用数组替换numOnesnumTwos等会很好。另外:您能否更明确地说明您遇到的问题?我猜在输出中打印正确数量的“#”。
  • 如果您的问题是生成重复的 # 字符串,那么这是 stackoverflow.com/questions/7107297/… 的重复项

标签: java loops random


【解决方案1】:

有一个这样的循环,你有你的打印语句。

修改你的代码,而不是每次都使用新变量,将它们放在一个数组中,这样你就可以遍历它们。

 import java.util.Scanner;

import java.util.Random;

public class DiceStats {

   public static void main(String[] args) {

      Scanner scnr = new Scanner(System.in);

      Random randGen = new Random();

      int seedVal = 11;

      randGen.setSeed(seedVal);

      // FIXME 1 and 2: Set the seed to the Random number generator


      int i = 0;          // Loop counter iterates numRolls times
      int numRolls = 0;   // User defined number of rolls 


      // FIXME 3: Declare and initiate cariables needed

      int[] numValues=new int[12];
      int die1 = 0;       // Dice 1 values
      int die2 = 0;       // Dice 2 values
      int rollTotal = 0;  // Sum of dice values

      System.out.println("Enter number of rolls: ");
      numRolls = scnr.nextInt();

      if (numRolls >= 1) {
         // Roll dice numRoll times
         for (i = 0; i < numRolls; ++i) {
            die1 = randGen.nextInt(6) + 1;
            die2 = randGen.nextInt(6) + 1;
            rollTotal = die1 + die2;

            // FIXME 4: Count number of sixs and sevens; complete the same for all other possible values
           numValues[rollTotal]++;
            System.out.println("Debugging: Roll " + (i+1) + " is " + rollTotal + " (" + die1 + 
          "+" + die2 + ")");
        }

         // Print statistics on dice rolls
         System.out.println("\nDice roll statistics:");

         // FIXME 5: Complete printing the histogram
        for(int i=2;i<=12;i++)
        {
           System.out.print(i+"s: ");
           for(int j=0;j<numVales[i];j++)
           {
               System.out.print("#");
           }
           System.out.println();
      }
      else {
         System.out.println("Invalid rolls. Try again.");
      }

     return;
   }
}

如果您需要澄清问题,请告诉我。

【讨论】:

    【解决方案2】:

    你可以这样做:

    public static void main(String[] args) {
    
        Scanner scanner = new Scanner(System.in);
        //You can directly set the seed during the object creation.
        Random random = new Random(System.currentTimeMillis());
        // This array is used to keep the value of your dice (2 - 12)
        int [] histogram = new int[13];
    
        while(true) {
            System.out.println("Enter number of rolls: ");
             int numberOfRolls = scanner.nextInt();
    
             //If you enter 0, you can simply terminate the program
             if(numberOfRolls == 0) break;
    
             for(int i = 0; i < numberOfRolls; i++) {
                 int rolledValue = (random.nextInt(6) + 1) + (random.nextInt(6) + 1);
                 histogram[rolledValue]++;
             }
    
             //Print the result to your console. 
             for(int i = 2; i < histogram.length; i++) {
                System.out.print("Total: " + i + " ");
                for(int j = 0; j <histogram[i]; j++) {
                    System.out.print("#");
                }
                System.out.println();
             } 
        }
    }
    

    该代码将产生如下结果:

    输入卷数:7

    总数:2

    总数:3#

    总数:4

    总数:5##

    总计:6

    总数:7###

    总数:8

    总数:9

    总数:10#

    总数:11

    总数:12

    【讨论】:

      【解决方案3】:

      看起来你真的很亲密。您只需要为您拥有的每个 int 变量打印 # 的数量。以下将为 numTwos 执行此操作:

               char[] chars = new char[numTwos];
               Arrays.fill(chars, '#');
               String result = new String(chars);
               System.out.println(result);
      

      您可以将整个内容放在 12 个循环中,以便为所有这些内容打印。

      【讨论】:

      • 我会把这个放在哪里?
      • 对不起.......而不是这一行: System.out.println("1s: " + numOnes);您可以将其替换为我列出的代码。这将打印出散列数(#####)而不是实际的 int。然后,你可以把整个事情循环起来,这样你就可以打印出第二个、第三个、第四个等等。
      • 如果您需要进一步说明,请告诉我。
      猜你喜欢
      • 2015-04-30
      • 2021-08-19
      • 2013-10-30
      • 1970-01-01
      • 2023-04-01
      • 2012-11-27
      • 2018-02-27
      • 1970-01-01
      相关资源
      最近更新 更多