我在第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)
答案 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]);
}