簡體   English   中英

數組列表存儲和檢查問題

[英]Array List storing and checking issue

我目前正在開發一個程序,該程序可以找到單詞中的第一個輔音。 這是來自主類的代碼:

            consonantLoop = 0;
            while(!consonantFound) {
                currentLetter = characters.get(consonantLoop);
                for(int x = 0; x < consonants.size(); x++) {
                     if(currentLetter == consonants.get(x)) {
                         consonantFound = true;
                         System.out.println("The first constanent in the word is " + consonants.get(x).toString());
                     } else {
                         consonantLoop++;
                     }
                }
            }

可變的consonantLoop是我用來確定所檢查的單詞的字母是否是元音的字母。 consonantFound是一個布爾值,它聲明是否已找到第一個輔音。 currentLetter是一個字符,用於定義我當前正在檢查的字母。 characters是存儲我的字符的arraylist。 consonants是存儲consonants的數組。 但是,當我運行代碼並且秒字母是輔音時,它給了我這個錯誤:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 42, Size: 3
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at testing.Main.main(Main.java:44)

第44行是currentLetter = characters.get(consonantLoop);
在@RajenRaiyare的幫助下,我能夠編輯我的代碼,因此不會再出現任何錯誤:

consonantLoop = 0;
while(!consonantFound) {
                try {
                    currentLetter = characters.get(consonantLoop);
                    for(int x = 0; x < consonants.size(); x++) {
                        if(currentLetter == consonants.get(x)) {
                            consonantFound = true;
                            System.out.println("The first consonant in the word is " + consonants.get(x).toString());
                        } else {
                            consonantLoop++;
                }
            }
        } catch(IndexOutOfBoundsException  e) {
            break;
        }
    }

但是現在在輸入單詞后,程序將終止。 問題是什么?

當前,您正在做的只是簡單地增加constantLoop計數器,而不檢查它是否小於要從中獲取記錄的arraylist的大小。 因此,如果constantLoop的值等於arraylist的大小,則它將給出IndexOutOfBoundsException。

解決此問題的兩種方法

1。

catch IndexOutOfBoundsException and do break from it.

2。

if (constantLoop < characters.size()) {
currentLetter = characters.get(constantLoop);
}else{
break;
}

您的代碼有兩個主要問題。 首先,當您到達列表的末尾時,您不會停止(或者在新版本中,您使用的是非常奇怪的方式)。 其次,你遞增consonantLoop一次, 輔音currentLetter不是。 您只需要對currentLetter每個值執行一次。 最簡單的增量方法是使用for循環,而不是使用while

for (int consonantLoop = 0; consonantLoop < characters.size() && !consonantFound;
        consonantLoop++) {
    ...
}

但是,完全使用循環計數器是不必要的復雜性。 for-each循環是一種遍歷characters內容的更干凈的方法。 在此過程中,我們可以通過調用contains方法來替換笨拙的內部循環:

for (Character c : characters) {
    if (consonants.contains(c)) {
        System.out.println("First consonant: " + c);
        break;
    }
}

break結束了循環,因為我們不能在for-each循環中使用consonantFound標志。

您沒有測試來避免consonantLoop超出characters大小,如果您得到的單詞沒有任何輔音。

您應該編寫循環:

while ((!consonantFound) && (consonantLoop < characters.length())) {
    ...
}

暫無
暫無

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

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