这是我隔离的代码:
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)
我迷失了。想法?我真的被困住了,现在已经和他们一起玩了一段时间。
答案 0 :(得分:4)
int index = scores[i];
counts[index]++;
根据randomInt(-5,15),索引可能是负数。
答案 1 :(得分:0)
更改
counts[index]
到
counts[index + 5]
这是因为index
来自a
数组,其元素初始化为-5
和14
之间的值。但是,只允许0
和29
之间的值作为counts
的索引,因此您需要添加5
。
答案 2 :(得分:0)
所以这就是你的代码所做的事情:
你从-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.
这就是导致你有异常的原因 希望这会有所帮助。