如果数组“a []”中有更多成员,则“b []”我收到错误

时间:2015-08-26 07:41:00

标签: java arrays

如果我把这个int a[]={2,5,8,8,9,4,9,8,9,6,4,7};,我收到以下错误:

  

线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException

如何解决这个问题?

public class Example {

    public static void main(String[] args) {

        int a[]={2,5,8,8,9,4,9,7};


        int b[]={1,5,8,5,6,2,9,8};

        int samenumber= 0;

        for(int i=0; i<a.length;  i++){ 
            if( a[i]==b[i]) {
                samenumber++;
            }


        }       
        System.out.println("The same numbers in the same index: "+ samenumber);         

    }

}

1 个答案:

答案 0 :(得分:0)

更正的代码。

public static void main(String [] args){

    int a[]={2,5,8,8,9,4,9,8,9,6,4,7};

    int b[] = { 1, 5, 8, 5, 6, 2, 9, 8 };

    int samenumber = 0;

    for (int i = 0; i < a.length; i++) {
        if (b.length > i) {
            if (a[i] == b[i]) {
                samenumber++;
            }
        } else {
            break;
        }

    }
    System.out.println("The same numbers in the same index: " + samenumber);

}