java.lang.ArrayIndexOutOfBoundsException:3错误

时间:2014-05-02 14:54:05

标签: java indexoutofboundsexception

我有以下代码,我将获得java.lang.ArrayIndexOutOfBoundsException

//divides ACode by 10 as many times as specified by the DecimalDigitPosition 
public static int getDecimalDigit(int ACode, int decimalDigitPosition) {
    if (decimalDigitPosition == 0)
        return ACode;
    else {
        ACode = ACode / (10 * decimalDigitPosition);
        int remainder = ACode % 10;
        return remainder;
    }
}

我怀疑这条线......

digit[i] = getDecimalDigit(samples[i].getValue(), 0);

在下面的代码中可能是此异常的原因。

//start a method to decode the message.
public static void decodeMessage(String filename) {
    Sound s = new Sound(filename);
    SoundSample[] samples = s.getSamples();
    int[] digit = new int[3];
    String message = "";
    int sampleIndex = 0;
    boolean nullReached = false;
    while (!nullReached) {
        int asciiValue = 0;
        for (int i = sampleIndex; i < sampleIndex + 3; i++) {
            if (i < samples.length) {
                // this line could be the cause of error..
                digit[i] = getDecimalDigit(samples[i].getValue(), 0);
                asciiValue += digit[i - sampleIndex] * (((i - sampleIndex) == 0) 
                ? 1 
                : ((i - sampleIndex) * 10));
            } else {
                for (int j = 0; j < 3; j++) {
                    digit[j] = 0;
                }
                break;
            }
        }
        if (digit[0] == digit[1] 
        && digit[1] == digit[2] 
        && digit[2] == 0) 
        nullReached = true;
        message += (char) asciiValue;
    }
}

堆栈跟踪:

  

java.lang.ArrayIndexOutOfBoundsException:3 at   project.decodeMessage(project.java:107)at   project.main(project.java:33)at   sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at   sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)   在   sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.jav一个:25)   在java.lang.reflect.Method.invoke(Method.java:597)at   edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:27 2)   &GT;

1 个答案:

答案 0 :(得分:1)

问题可能出现在decodeMessage方法中。我已经删除了一些代码来解决问题:

int[] digit = new int[3];
while (!nullReached)
{
    for (int i = sampleIndex; i < sampleIndex + 3; i++)
    {
        if (i < samples.length)
        {
            digit[i] = getDecimalDigit(samples[i].getValue(), 0);   // This should be the line that throws the exception                
        }               
    }           
    sampleIndex += 3;           
}

第二次通过while循环,sampleIndex将为3,因此i将从3开始。然后,您尝试取消引用digit[i],即digit[3]。由于digit[]int[3],因此digit[3]超出了数组的范围。

也许你想这样做:

digit[i-sampleIndex] = getDecimalDigit(samples[i].getValue(), 0);