簡體   English   中英

arraylist java上的IndexOutOfBoundsException

[英]IndexOutOfBoundsException on arraylist java

我正在通過ContextQuery方法在數據庫中尋找等效單詞,當等效單詞為null時,程序必須嘗試使用​​單詞中的下一個索引,並將其加到當前單詞中,以使其成為兩個單詞,如果兩個單詞仍然為空,程序將使其變成三個單詞,尋找下一個2值,現在正在控制台中打印等效單詞,但運行后出現錯誤IndexOutOfBoundsExpection

        for (int i = 0; i < words.size(); i++){
        temp = QueryWithContext.query(words.get(i));
            if((temp == null || temp.isEmpty()) && words.size() >= i+1)
            {
            QueryWithContext.query(words.get(i)+" "+words.get(i+1));
            temp = QueryWithContext.query(words.get(i)+" "+words.get(i+1));
            System.out.println("1st if");
                if((temp == null || temp.isEmpty()) && words.size() >= i+2)
                    {
                    temp = QueryWithContext.query(words.get(i)+" "+words.get(i+1)+" "+words.get(i+2));
                    }
                    else
                    {
                        temp = words.get(i);
                    }

            }



            System.out.println(temp);
if((temp == null || temp.isEmpty()) && words.size() >= i+1)

一定是

if((temp == null || temp.isEmpty()) && words.size() > i+1)

除此以外

words.get(i+1)

拋出IndexOutOfBoundsExpection。

此行最有可能出現問題: temp = QueryWithContext.query(words.get(i)+" "+words.get(i+1)+" "+words.get(i+2)); 您一直循環播放,直到i小於words的大小,因此i范圍是0到n - 1

問題在於,在您的代碼中,您將一直進行到i + 2 (以前是i + 1 )。 這是最有可能導致您的錯誤的原因。 要解決此問題,請查看是否可以執行以下操作: for (int i = 0; i < (words.size() - 2); i++){

或者,按照@Uli的建議進行操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM