在编译程序时,我得到了ArrayIndexOutOfBound异常

时间:2017-06-29 05:40:53

标签: java

我在第14行收到ArrayIndexOutOfBound例外。

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);

}

}

我得到的例外是:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
   at str.files.Duplicate.main(Duplicate.java:14)

2 个答案:

答案 0 :(得分:0)

您只能循环到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]);    
}

答案 1 :(得分:0)

由于您使用i+1内部循环,因此您可以使用小于i的值dup.length - 1,否则您将超出数组的范围。

也从i=0开始,这是数组的开头。

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]);    
}