我的java程序给了我一个IndexOutOfBoundsException

Len*_*mes 0 java runtime-error indexoutofboundsexception

当我的程序进入我的代码的这一部分时,它会崩溃并产生此错误

public static boolean Search(ArrayList<String> ArrayToSearch,String word)
{
    String temp;
    boolean found = false;
    for(int counter = 0;found || counter < ArrayToSearch.size();counter++)
        {
        temp = ArrayToSearch.get(counter);
        if(temp.equals(word.toLowerCase()))
        {
            found = true;
            position = counter;
        }
    }
    return found;
}
Run Code Online (Sandbox Code Playgroud)

ArrayToSearch是不同的数组列表,每行包含一个单词,代表字典.Word是用户想要搜索的单词.这是它产生的错误.Add是一个调用此方法并从中接收一个布尔值的方法

D:\>java Evan
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 109680, Size: 109680
        at java.util.ArrayList.rangeCheck(Unknown Source)
        at java.util.ArrayList.get(Unknown Source)
        at Evan.Search(Evan.java:95)
        at Evan.Add(Evan.java:68)
        at Evan.main(Evan.java:53)

D:\>
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

这就是问题:

found || counter < ArrayToSearch.size()
Run Code Online (Sandbox Code Playgroud)

如果found永远变为现实,那将永远持续- 或者更确切地说,直到它因为这个例外而爆炸.我怀疑你的意思

!found && counter < ArrayToSearch.size()
Run Code Online (Sandbox Code Playgroud)

换句话说:"在我们没有找到这个词的同时继续前进,还有更多的收藏要透过."

但是,只要在找到结果后直接返回就会更清楚.如果使用增强的for循环,它也会更简单:

// Names change to follow conventions
public static boolean search(List<String> list, String word) {
    // TODO: Handle the possibility of anything being null
    for (String candidate : list) {
        if (candidate.equals(word)) {
            return true;
        }
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

或者甚至更简单,只需使用List.contains已经这样做.