轧制m面,n面x次

时间:2013-12-09 20:41:59

标签: java for-loop indexoutofboundsexception dice

好的,所以我改变了我的代码并删除了很多不必要的垃圾。它适用于某些数字,但不适用于其他数字,例如,当我放入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)+"%");                                                   
    }
}

1 个答案:

答案 0 :(得分:0)

有两个基本问题:

  1. 添加滚动总计时,您尝试在数组末尾的索引中添加最大滚动。简单的解决方法是简单地在数组长度上加1。
  2. 打印时,您无法使用等于数组长度的索引访问数组,这是m<=rollSum.length最终将执行的操作。将其替换为m < rollSum.length,使其在最终值之前停止。

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

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

    我还建议拆分该print语句。它更容易阅读和调试。此外,您可以从numDie开始而不是2来解释当您的死亡人数多于或少于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 + "%");
        }