0

So I am creating a program that rolls z die x times with y sides, and I keep getting an out of bounds error at the first line in the first for loop. However I'm not sure why this is, the loop counts from 0 to (z-1). I'm basically in the home stretch of this program and I need the help of the stackoverflow community.

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 x = console.readInt();
        System.out.print("Enter the amount of sides: ");
        int y = console.readInt();          
        System.out.print("Enter the amount of die: ");
        int z = console.readInt();      
        int[][] dice = new int[x][z];
        int row = 0;
        for (int i = 0; i<z; ++i){
             dice[row][i] += ((int)(Math.random()*y)+1);
             if ((i == z-1)&&(row!=x)) {
                i = 0;
                ++row;
             }
        }     
        row = 0;
        int[] sum = new int[x];
        for (int j = 0; j<z; ++j){
            sum[row]+=dice[j][row];
            if ((j == z-1)&&(row!=x)) {
                j = 0;
                ++row;          
            }
        }                                                                                                                                                                                           
        int[] counter = new int[2*y];
        int k = 0;
        while (k<sum.length){
            for (int l = 0;l<((2*y)-1);++l){
                if (sum[k]==l) ++counter[l];
                if (l==((2*y)-1)) {
                    ++k;
                }
            }
        }   
        for (int m = 0;m<sum.length;++m) System.out.println(sum[m]+"'s: "+counter[m]+"times, "+((((double)counter[m])/x)*100)+"%");                                                   
    }
}
Showman
  • 55
  • 2
  • 6

2 Answers2

0

first loop:

for (int i = 0; i<z; i++){
  dice[row][i] += ((int)(Math.random()*y)+1);
  if ((i == z-1)&&(row!=x-1)) {
    i = -1;
    ++row;
  }
}

second loop:

for (int j = 0; j<z; j++){
  sum[row]+=dice[j][row];
  if ((j == z-1)&&(row!=x-1)) {
    j = -1;
    ++row;          
  }
} 

Third loop: runs forever. I'm not sure what this is trying to achieve, so I can't fix it for you...

M21B8
  • 1,867
  • 10
  • 20
  • also, probably worth reading: http://stackoverflow.com/questions/24853/what-is-the-difference-between-i-and-i – M21B8 Dec 06 '13 at 15:20
0

There are x rows but you are using z as the row loop

int[][] dice = new int[x][z]; <-- x is the row count
int row = 0; 

for (int i = 0; i < z; ++i){  <--- The outer loop is iterating the rows (x), 

Here's how to iterate through a 2D array

int[][] dice = new int[x][z];

for (int i = 0; i < x; i++){
   for (int j = 0; j < z; j++){
      // do something with dice[i][j]
   }
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720