下面是一个搜索连续字符的简单程序。但是,我遇到了异常,因为我正在数组索引之外进行搜索。我明白为什么会发生这种情况,但不确定如何处理?
public static void main(String [] args)
{
String term = "Popeye's fishCat";
String query = "P's SalmonCat";
int score = 0;
char [] termChar = term.toCharArray();
char [] queryChar = query.toCharArray();
if((queryChar[0]) == (termChar[0]))
{
score++;
}
for(int i = 0; i < queryChar.length; i++)
{
for(int j = 0; j < termChar.length; j++)
{
if(queryChar[i] == termChar[j] )
{
if((queryChar[i + 1]) == (termChar[j + 1])) //Causes an exception
{
System.out.println((queryChar[i + 1]) + " " + (termChar[j + 1]));
score++;
break;
}
}
}
}
System.out.println(score);
}
最佳答案
调整循环条件:
for(int i = 0; i < queryChar.length - 1; i++) {
for(int j = 0; j < termChar.length - 1; j++)
注意添加的-1
如果您总是查看循环中的下一个项目,则无法循环到最后一个项目,因为它没有下一个项目。
关于java - 我如何管理 ArrayIndexOutOfBounds,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17433058/