-11

I am getting ArrayIndexOutOfBound exception in line 14.

package str.files;

public class Duplicate {

public static void main(String[] args)
{
    int count=0;
    String s="this is a java  is program ";
    String[] dup= s.split(" ");

    for(int i=1;i<=dup.length;i++)
    {
        //System.out.println(dup[i]);
        if(dup[i].equalsIgnoreCase(dup[i+1]))
        {

            count++;
        }           
        System.out.println("The duplicate character is : :"+dup[i]);    
    }

    System.out.println("no. of occurances of the program is : "+count);

}

}

The exception I'm getting is :

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
   at str.files.Duplicate.main(Duplicate.java:14)
ItamarG3
  • 4,092
  • 6
  • 31
  • 44
manish
  • 1
  • 1

2 Answers2

0

You only loop to dup.length - 1.

for(int i=1;i<dup.length - 1;i++)
{
    //System.out.println(dup[i]);
    if(dup[i].equalsIgnoreCase(dup[i+1]))
    {

        count++;
    }           
    System.out.println("The duplicate character is : :"+dup[i]);    
}
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Tien Nguyen Ngoc
  • 1,555
  • 1
  • 8
  • 17
0

Because you use i+1 inside loop you can reach value i with less than dup.length - 1, otherwise you will go outside the bounds of the array.

Also start with i=0 which is the start of the array.

for(int i=0; i<dup.length - 1; i++) {
    //System.out.println(dup[i]);
    if(dup[i].equalsIgnoreCase(dup[i+1])) {
        count++;
    }           
    System.out.println("The duplicate character is : :"+dup[i]);    
}
Ori Marko
  • 56,308
  • 23
  • 131
  • 233