This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
                                
                                    (25个答案)
                                
                        
                在8个月前关闭。
            
        

我必须检查任何数字的序列是否相等。用户将提交一个序列,如果数字按序列重复,他将获得一些积分。

赢得积分的顺序是三个顺序。例如:
1 3 4 4 4 5
他赢得了积分,因为他输入了3个数字4的序列。

它在矢量上的数字序列。向量的大小,也由用户指定。

for (int i = 0; i < M.length; i++) {
            if (M[i] == M[i + 1] && M[i + 1] == M[i+2]) {
                if (L[i] == L[i + 1] && L[i + 1] == L[i + 2]) {
                    ValuePoint = 0;
                } else {
                    PExtraM = i;
                    ValuePoint = 30;
                }

Scanner sc1 = new Scanner(System.in);

        R = sc1.nextInt();

        int M[] = new int[R];
        int L[] = new int[R];

        for (int i = 0; i < M.length; i++) {
            M[i] = sc1.nextInt();
        }

        for (int i = 0; i < L.length; i++) {
            L[i] = sc1.nextInt();
        }


//The problem It's here ************************************


        for (int i = 0; i < M.length; i++) {
            if (M[i] == M[i + 1] && M[i + 1] == M[i+2]) {
                if (L[i] == L[i + 1] && L[i + 1] == L[i + 2]) {
                    ValuePoint = 0;
                } else {
                    PExtraM = i;
                    ValuePoint = 30;
                }


线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:5
    在maratona.Maratona2.main(Maratona2.java:37)
Java结果:1

最佳答案

正如其他人已经说过的那样,您可能会超出阵列的边界。您需要提前停止循环2来防止。
您可能想使用类似这样的东西:

    int sequenceLength = 3;
    for (int i = 0; i <= M.length - sequenceLength; i++) {
        boolean correct = true;
        for (int j = 0; j < sequenceLength && (correct = (M[i] == M[j+i])); j++);

        if (correct){
            ValuePoint = 0;
        } else {
            PExtraM = i;
            ValuePoint = 30;
            break;
        }
    }

09-30 14:21
查看更多