删除ArrayIndexOutOfBoundsException

时间:2015-07-03 17:00:02

标签: java exception main indexoutofboundsexception

以下程序导致ArrayIndexOutOfBoundsException。我有两个数组s1s2

代码:

/* IMPORTANT: class must not be public. */


import java.io.BufferedReader;
import java.io.InputStreamReader;

class TestClass {
    public static void main(String args[] ) throws Exception {


    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String s1="",s2="";
    int c=0,a=0;

          int T = Integer.parseInt(br.readLine());
        while(T-->0)
        {
            s1=br.readLine();
            String ars1[]=s1.split(" ");
            int N=Integer.parseInt(br.readLine());
            while(N-->0)
            {
                s2=br.readLine();
                String ars2[]=s2.split(" ");

                for(int i=0;i<ars1.length;i++)
                {
                    for(int j=0;j<ars2.length;j++)
                    {
                        if(ars2[i]==ars1[j])
                        {
                            c++;
                            continue;
                        }
                    }
                }
                if(c==ars1.length)
                a++;
            }
        }

        System.out.println(a);
    }
}

如何解决?

1 个答案:

答案 0 :(得分:1)

正如@skandigraun在评论中指出的那样,

在,

for(int i=0;i<ars1.length;i++)
                {
                    for(int j=0;j<ars2.length;j++)
                    {
                        if(ars2[i]==ars1[j])
                        {
                            c++;
                            continue;
                        }
                    }
                }

ars2[i] == ars1[j]似乎不正确,因为您无法确定这些数组的索引边界

此处i对应ars1的计数器,j对应ars2的计数器。

交换它们应该摆脱异常