【问题标题】:Out of Bounds Error in 2D Array with Dice Program使用 Dice 程序的 2D 阵列中的越界错误
【发布时间】:2013-12-23 23:47:09
【问题描述】:

所以我正在创建一个程序,该程序用 y 边滚动 z die x 次,并且在第一个 for 循环的第一行中不断出现越界错误。但是我不确定为什么会这样,循环从 0 计数到 (z-1)。我基本上处于这个程序的最后阶段,我需要 stackoverflow 社区的帮助。

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)+"%");                                                   
    }
}

【问题讨论】:

    标签: java arrays matrix indexoutofboundsexception dice


    【解决方案1】:

    有 x 行,但您使用 z 作为行循环

    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), 
    

    以下是遍历二维数组的方法

    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]
       }
    }
    

    【讨论】:

      【解决方案2】:

      第一个循环:

      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;
        }
      }
      

      第二个循环:

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

      第三个循环:永远运行。我不确定这是要达到什么目的,所以我无法为您解决它...

      【讨论】:

      猜你喜欢
      • 2018-01-20
      • 2022-01-13
      • 2022-08-24
      • 2015-01-19
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多