ArrayIndexOutOfBoundsException但我无法看到它超出界限的位置

时间:2014-12-05 15:46:00

标签: java arrays runtime-error

完整错误是:

java.lang.ArrayIndexOutOfBoundsException: 7 at Taskone.main(Taskone.java:15)

我的完整代码是:

import java.io.*;

public class Taskone
{
    public static void main(String[] args) throws IOException
    {
        int experiments = 10;
        int[] arrayone = new int[ 14 ];
        Die die = new Die();

        for(int i=0; i<experiments ;i++) {
            int d1 = die.roll();
            int d2 = die.roll();
            int dT = d2 + d1 ;
            arrayone[dT]++; //Line which throws the exception

        }

        for(int j=0; j<arrayone.length; j++) {
            System.out.println("The amount of " + j + " rolled as a combination of two dice is: " + arrayone[j]); 

        }

    }

}

我的骰子代码:

public class Die
{
    int roll()
    {
        double x = Math.random();
        x = 1.0 + (x * 6.0);
        int outcome = (int)Math.floor(x);

        return outcome;
    }    
}

我不确定为什么我会收到此错误,虽然我可以看到我被告知它是导致错误的行arrayone[dT]++;。 有人可以指出我正确的方向并纠正我吗?

4 个答案:

答案 0 :(得分:0)

这段代码有效,我只是以1000000的循环运行它。最简单的解决方案可能只是创建一个新项目并将代码复制到该项目中。

答案 1 :(得分:-1)

您需要确保将arrayone的大小设置为至少包含Die.roll()可返回的最大值的两倍。

我运行了您目前提供的代码并生成了以下内容:

The amount of 0 rolled as a combination of two dice is: 0
The amount of 1 rolled as a combination of two dice is: 0
The amount of 2 rolled as a combination of two dice is: 2
The amount of 3 rolled as a combination of two dice is: 1
The amount of 4 rolled as a combination of two dice is: 1
The amount of 5 rolled as a combination of two dice is: 0
The amount of 6 rolled as a combination of two dice is: 1
The amount of 7 rolled as a combination of two dice is: 2
The amount of 8 rolled as a combination of two dice is: 2
The amount of 9 rolled as a combination of two dice is: 0
The amount of 10 rolled as a combination of two dice is: 0
The amount of 11 rolled as a combination of two dice is: 1
The amount of 12 rolled as a combination of two dice is: 0
The amount of 13 rolled as a combination of two dice is: 0

您是否对代码进行了其他更改?

答案 2 :(得分:-1)

使用try / catch:

围绕您对arrayone的访问
try {
  arrayone[dT]++;
} catch (ArrayIndexOutOfBoundsException e) {
  System.out.println("The value of d1 is " + d1);
  System.out.println("The value of d2 is " + d2);
}

然后你会看到你做出的假设是假的。

答案 3 :(得分:-2)

数组大小为14,您试图在索引处插入的值超过13。