【问题标题】:Rolling m die with n sides x times滚动 n 面的 m 模具 x 次
【发布时间】:2013-12-27 03:15:47
【问题描述】:

好的,所以我更改了我的代码并删除了其中很多不必要的垃圾。它适用于某些数字,但不适用于其他数字,例如,当我放入 100 个卷/8 个面/3 个骰子时,尽管我为它设置了限制,但它给了我一个超出范围的错误。显然我已经查看了一些细节,我只是不确定它是什么细节。

public class Ass11f {

    public static void main(String[] args) {
        EasyReader console = new EasyReader();
        System.out.print("Enter how many times you want to roll the die: "); 
        int numRolls = console.readInt();
        System.out.print("Enter the amount of sides: ");
        int numSides = console.readInt();           
        System.out.print("Enter the amount of die: ");
        int numDie = console.readInt();     
        int[] rollSum = new int[numDie*numSides];

        for (int i = 0; i<numRolls; ++i)
            {
            int rollCounter=0;
            for (int l = 0; l<numDie; ++l){
                rollCounter += ((int)(Math.random()*numSides)+1);
            }
            rollSum[rollCounter]++;
        }     
        for (int m = 2;m<=rollSum.length;++m) System.out.println(m+"'s: "+rollSum[m]+" times, "+((((double)rollSum[m])/numRolls)*100)+"%");                                                   
    }
}

【问题讨论】:

  • rollSum[rollCounter]++; 究竟应该做什么?你能用实际的堆栈跟踪edit你的答案吗?
  • @thegrinner 它应该在rollSum的rollCounter值的索引处增加元素。
  • 您是否尝试跟踪某个值的滚动次数?你能澄清最终目标吗?我在考虑 rollSum 的目的时遇到了一些麻烦。
  • @thegrinner 该程序应该像我说的那样用 y 边 z 次掷 x 骰子,并总结每卷所有骰子的总数并显示每个总和。
  • 那么 rollSum 中的每一项都是该卷的总和?还是到那时为止的累积总和?另外,是第一个循环(int i)还是第二个循环(int m)给你一个异常?

标签: java for-loop indexoutofboundsexception dice


【解决方案1】:

有两个基本问题:

  1. 当添加滚动总数时,您尝试将最大滚动添加到数组末尾之后的索引中。简单的解决方法是简单地将数组的长度加 1。
  2. 打印时,您无法使用等于数组长度的索引访问数组,m&lt;=rollSum.length 最终会这样做。将其替换为 m &lt; rollSum.length,使其在最终值之前停止。

另外,这里有一些方法可以让你的数组创建更加清晰:

    // The minimum value is always numDie.
    // The maximum is always numDie * numSides
    // There are maximum - minimum + 1 possible values (ie 6 on a d6)
    int maximum = numDie * numSides;
    int minimum = numDie;

    // Remember, index zero is now the minimum roll. 
    // The final index is the maximum roll. So the count at an index is really
    // the count for any roll with value index + minimum
    int[] rollSum = new int[maximum - minimum + 1];

我还建议拆分该打印语句。它更容易阅读和调试。此外,您可以从 numDie 而不是 2 开始,以说明您的 die 多于或少于 3:

    for (int i = numDie; i < rollSum.length; ++i) {
        // Print the first bit, ie "2's: ".
        System.out.print(i + "'s: ");

        // How many times was that value rolled?
        System.out.print(rollSum[i] + " times, ");

        // What percentage is that?
        double percentage = ((double)rollSum[i]) / numRolls * 100;
        System.out.println(percentage + "%");
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    相关资源
    最近更新 更多