-1

The following program results in an ArrayIndexOutOfBoundsException. I have two arrays s1 and s2.

Code:

/* 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);
    }
}

How to fix it?

Sailesh Sriram
  • 144
  • 2
  • 17
pj2494
  • 111
  • 7

1 Answers1

1

As @skandigraun had pointed out in the comments,

In,

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] seems to be incorrect as you can't be certain of the index bounds of these arrays.

Here i corresponds to the counter for ars1 and j corresponds to counter for ars2.

Interchanging them should get rid of the exception.

Sailesh Sriram
  • 144
  • 2
  • 17