-1

So, I'm working on a problem that has me adding two die rolls 'X' amount of times, then recording the frequency in an array, here is what I have

int [] counters = new int [11];
    for (int i = 0; i <1001; i++){
        //have to add +1 so I don't get 0
        ++counters[((die1.nextInt(6)+1)+(die2.nextInt(6)+1))];
    }
    System.out.print(counters);

And I'm getting this error: java.lang.ArrayIndexOutOfBoundsException: 12

2 Answers2

1
//have to add +1 so I don't get 0

No you really don't.

In Java arrays are 0-based. Meaning an array of 11 elements has indices 0 .. 10.

Random.nextInt(n) returns a value between 0 and n-1.

Therefore the expression ((die1.nextInt(6)+1)+(die2.nextInt(6)+1)) will be between 2..12.

Either increase the size of the array to 13 so that 12 fits (the first 2 elements will remain unused), or simply remove +1's:

    Random die1 = new Random(), die2 = new Random();
    int [] counters = new int [11];
    for (int i = 0; i <1001; i++){
        ++counters[die1.nextInt(6)+die2.nextInt(6)];
    }

Also you can't print an array with print(). A possible solution is to print each element individually:

    for (int i = 0; i < counters.length; ++i) {
        System.out.print((i+1) + ":" + counters[i] + " ");
    }
    System.out.println();
rustyx
  • 62,971
  • 18
  • 151
  • 210
  • Personally I am not a fan of having empty elements in the array. If you really wanted to keep the mental mapping of dice rolls to values I would prefer to convert the results into a map (preferably unmodifiable) afterwards or something similar. – Stalemate Of Tuning Jan 18 '19 at 18:07
0

You have two dice, and the result of a die roll can be from 0 to 5. I assume the 1001 means you want to roll the two dice 1001 times. Please let me know if I missed anything here.

In this case your min roll would be a 0, and max 10. But, adding 1 to both dice rolls before accessing would mean your index goes from 2 to 12 which causes your ArrayIndexOutOfBoundsException.

Just don't add anything to the roll. Remember java arrays start from 0, so a range of 0 to 10 is fine.

Quick example:

public static class Die {
    static Random rand = new Random();

    public static int nextInt(int val) {
        return rand.nextInt(val);
    }
}

public static void main(String[] args) {
    int[] counters = new int [11];
    for (int i = 0; i <1001; i++){
        //no need to add anything
        ++counters[Die.nextInt(6) + Die.nextInt(6)];
    }
    System.out.print(Arrays.toString(counters));
}

Example output:

[27, 60, 81, 106, 157, 175, 120, 109, 81, 55, 30]

Which we can translate to mean that a "2" was rolled 27 times, "3" 60 times, etc.