Search code examples
arraysindexoutofboundsexception

How to fix this index out of bounds error?


So basically what I am supposed to do is I am supposed to get an arraylist of strings and fill it with two strings and compare them. For example if one string is "1,2,3,4" and the second one is "7,6,2,8,1" it's supposed to print out "1,2" because it prints out the numbers that are similar. But I'm getting and arrayindexoutofbounds exception and I couldn't figure out how to fix it. Also, if you have ANY tips whatsoever to possibly shorten this code please tell me as well. I have a habit of making my code super long.

import java.util.*;
public class Compare
{
 public static void main(String[]args)
 {
   ArrayList<String> hap=new ArrayList<String>();
   hap.add("1,7,8,2");
   hap.add("6,2,4,10,8");
  String ar1=hap.get(0);
   String ar2=hap.get(1);
   String[]arr1=new String[ar1.length()];
   String[]arr2=new String[ar2.length()];
   for(int i=0;i<ar1.length();i++)
   {
    if(ar1.charAt(i)!=(','))
    {
      arr1[i]=""+ar1.charAt(i);
    }
     }
   for(int i=0;i<ar2.length();i++)
   {
    if(ar2.charAt(i)!=(','))
    {
      arr2[i]=""+ar2.charAt(i);
    }
   }
   ArrayList<String> b=new ArrayList<String>();
   int ah=0;
   while(ah<arr1.length)
   {
    for(int i=0;i<arr2.length;i++)
    {
     if(arr1[ah]==arr2[i])           //error on this line
     {
       b.add(arr1[ah]);
     }
     ah++;
    }
   }
   for(int i=0;i<b.size();i++)
   {
     System.out.println(b.get(i));
   }
 }
}



Solution

  • here instead of manually creating an arrays from string, you can use String.split() method to split an string with , this will return the new array. and you are getting an exception because length of arr1 is less then arr2. while you increment ah++ in arr2 loop.

    Below code will fix your issue and reduce the code size.

    import java.util.*;
    public class Main
    {
        public static void main(String[] args) {
            ArrayList<String> hap=new ArrayList<String>();
       hap.add("1,7,8,2");
       hap.add("6,2,4,10,8");
      String ar1=hap.get(0);
       String ar2=hap.get(1);
       String[] arr1=ar1.split(",");
       String[] arr2=ar2.split(",");
       ArrayList<String> b=new ArrayList<String>();
       for(int j=0;j<arr1.length;j++)
       {
        for(int i=0;i<arr2.length;i++)
        {
         if(arr1[j].equals(arr2[i]))           //error on this line
         {
           b.add(arr1[j]);
         }
        }
       }
       for(int i=0;i<b.size();i++)
       {
         System.out.println(b.get(i));
       }
        }
    }