【问题标题】:Histogram project: code throws ArrayIndexOutOfBoundsException直方图项目:代码抛出 ArrayIndexOutOfBoundsException
【发布时间】:2013-12-01 01:00:02
【问题描述】:

这是我分离出来的代码:

public static void randomIntArray(int n) {
    int[] a = new int[n];
    for (int i = 0; i < a.length; i++) {
        a[i] = randomInt(-5, 15);
    }
    scoreHist(a);
}

public static void scoreHist(int[] scores) {
    int[] counts = new int[30];
    for (int i = 0; i < scores.length; i++) {
        int index = scores[i];
        counts[index]++;
    }
}

但是每当我运行它时,它都会给我这个:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: (Insert Random # Here)
    at arrayhistogram.ArrayHistogram.scoreHist(ArrayHistogram.java:39)
    at arrayhistogram.ArrayHistogram.randomIntArray(ArrayHistogram.java:31)
    at arrayhistogram.ArrayHistogram.main(ArrayHistogram.java:21)

我迷路了。想法?我真的被困住了,并且已经在这个圈子里转了一段时间。

【问题讨论】:

  • +1 用于隔离问题。
  • 你在函数 randomIntArray 上传递了什么 int 值?确保它不大于计数的长度。确保随机化正值。

标签: java histogram


【解决方案1】:
int index = scores[i];
counts[index]++;

根据 randomInt (-5,15),索引可能为负数。

【讨论】:

    【解决方案2】:

    改变

    counts[index]
    

    counts[index + 5]
    

    这是因为 index 来自 a 数组,其元素被初始化为介于 -514 之间的值。但是,只有 029 之间的值才允许作为 counts 的索引,因此您需要添加 5

    【讨论】:

    • 另外,还有内存优化的空间:int[] counts = new int[20];
    【解决方案3】:

    这就是你的代码所做的事情:

    你从 -5 到 15 中选择“n”个随机数(比如 n=5),将它们推入一个数组中

    说,数组变成了

    scores[] = {0,1,1,5,-3}
    

    现在,您将在scoreHist() 中传递这个创建的数组。

    现在,查看运行时变量的状态

       i       scores[i]        index               counts[index]
      ---      ---------        -----           ----------------------
    //1st iteration
       0      scores[0]=0         0           counts[0]=counts[0]+1 -> 1       
    Everything goes fine in the first iteration.
    //2nd iteration
       1      scores[1]=1         1           counts[1]=counts[1]+1 -> 1
    Everything goes fine here as well. Now "counts[] = {1,1}"
    //3rd iteration
       2      scores[2]=1         1           counts[1]=counts[1]+1 -> 2
    Things go alright. counts[1] has been updated. Now "counts[] = {1,2}"
    //4th iteration
       3      scores[3]=5         5           counts[5]=counts[5]+1 -> 1
    Things go absolutely fine here . 
    //5th iteration
       4      scores[4]=-3        -3          counts[-3] !!!!!!!! It is out of bound limits for the       
                                                                  array. This index does not exist.
    

    这就是导致您遇到异常的原因 希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-09
      • 2023-03-16
      • 1970-01-01
      • 2012-04-12
      • 2013-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多