for循环中的ArrayIndexOutOfBoundsException

时间:2015-09-22 19:00:55

标签: java for-loop indexoutofboundsexception

这里我的数字长度超过9位数,将数字分成9位数组并将其存储在数组中。 当我运行此代码将值存储在arrayOfNumbers中时,我抛出了一个ArrayIndexOutOfBoundsException。

 public BigNum(String s) {
    if (badNum(s)) {
        throw new IllegalArgumentException();     //Exception to check for invalid input
    }

    int arraySize = 1;
    num = s;
    int [] arrayOfNumbers = new int[arraySize];
    int numSize = s.length();

    if (numSize <= 9)
    {
        arraySize = 1;
        arrayOfNumbers[0] = Integer.parseInt(s);         //THIS CLAUSE IS WORKING
    }
    else if((numSize % 9) >= 1) {
        arraySize = ((numSize % 9) + 1);
        int x = 0;
        int y = 9;
        int[] evenString = new int[arraySize];                  
        for (int i=0; i < arraySize; i++){


            String w = s.substring(x,y);

            arrayOfNumbers[i] = Integer.parseInt(w); //THIS LINE IS FAILING *********

            if(i == arraySize - 2){
                x = x + 9;
                y = y + (numSize % 9);
            }
            else{
                y = y + 9;
                x = x + 9;
            }


        }

        System.out.println(arraySize);
    }
    else if((numSize % 9 == 0)) {
        arraySize = (numSize/9);

        int x = 0;
        int y = 9;

        for (int i=0; i < arraySize; i++){

            String w = s.substring(x,y);
            int[] evenString = new int[arraySize];      //THIS CLAUSE IS WORKING

            y = y*2;
            x = x+9;

        }
    }
}

1 个答案:

答案 0 :(得分:0)

问题是您正在分配初始化为只有一个元素的arrayOfNumbers。你的意思是分配给evenString吗? evenString用这个循环的正确数组大小初始化。

您也可以将arrayOfNumbers声明为与evenString数组相同的大小。例如:

int[] arrayOfNumbers = new int[arraySize];                  
for (int i=0; i < arraySize; i++){


    String w = s.substring(x,y);

    arrayOfNumbers[i] = Integer.parseInt(w); //THIS LINE IS FAILING *********

    if(i == arraySize - 2){
        x = x + 9;
        y = y + (numSize % 9);
    }
    else{
        y = y + 9;
        x = x + 9;
    }
}