随机化器中的索引超出范围异常错误

时间:2015-08-12 22:58:03

标签: java arrays

我刚刚开始编程并且正在尝试制作一个随机数字,其中会生成一个随机数,并且该随机数将与一个名称相关联,然后该名称会出现,我无法弄清楚我的问题代码,这是弹出的错误

"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
    at random.Randomiser.main(Randomiser.java:21)" 

package random;

public class Randomiser {

    public static void main(String[] args) {

        int number = ((int) (Math.random()*10))+1;

        int[] intArray = new int[9];

        intArray[0] = 1;
        intArray[1] = 2;
        intArray[2] = 3;
        intArray[3] = 4;
        intArray[4] = 5;
        intArray[5] = 6;
        intArray[6] = 7;
        intArray[7] = 8;
        intArray[8] = 9;
        intArray[9] = 10;

        if (number == 1) 
            System.out.println("Isaac");
        if (number == 2) 
            System.out.println("Madgeline");
        if (number == 3) 
            System.out.println("Cain");
        if (number == 4) 
            System.out.println("Judas");
        if (number == 5) 
            System.out.println("Blue Baby");
        if (number == 6) 
            System.out.println("Eve");
        if (number == 7) 
            System.out.println("Samson");
        if (number == 8) 
            System.out.println("Azazel");
        if (number == 9) 
            System.out.println("Lazarus");
        if (number == 10) 
            System.out.println("Eden");
    }
}

3 个答案:

答案 0 :(得分:0)

更改数组大小。现在,您的尺寸为9,最大索引为8

int[] intArray = new int[10];

答案 1 :(得分:0)

这里有索引0到8。你没有第9个索引。       int[] intArray = new int[9];将其更改为int[] intArray = new int[10]或删除intArray[9] = 10;

你可以像这样int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

声明你的数组

答案 2 :(得分:0)

您必须像这样创建数组:

int[] intArray = new int[10]; 

创建数组时,请指定大小:

int[] intArray = new int[9];  // size is 9

当你访问它时,你从位置0开始,所以当你这样做时:

intArray[9] = 10; 
// you're accessing to a non created position of the array 
// max position is intArray[8] then:
// IndexOutOfBounds exception is thrown.