簡體   English   中英

線程“main”中的異常 java.lang.StringIndexOutOfBoundsException:字符串索引超出范圍:5

[英]Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5

我的代碼有什么問題(線程“main”java.lang.StringIndexOutOfBoundsException 中的異常:字符串索引超出范圍:5)........

public class AAExample {
    public static void main(String[] args) {
        AAExample nn = new AAExample();
        System.out.println(nn.isXOrZ("Pony"));
    }

    public  boolean isXOrZ(String text) {
    String  lower = text.toLowerCase();
    boolean found = false;
    int     i     = 0;

    while (!found) {
        String letter = lower.substring(i, i +1);

            if(letter.equals("z") || letter.equals("x"))
            found = true;

            i++;
        }

        return found;
    }
}

您的 while 循環不斷循環,直到找到xz 當您的String實際上沒有xz時,就會發生無限循環。

StringIndexOutOfBoundsExceptioni >= lower.length()-1

所以你需要修改你的while循環

 while (!found && i < lower.length()-1)

您的循環終止條件僅取決於是否找到字符。

while (!found)

假設,你沒有發現任何東西,那么你永遠不會做

if(letter.equals("z") || letter.equals("x"))
   found=true

並繼續增加i ,一旦它等於字符串的長度,它就會給你 StringIndexOutOfBoundsException

您正在遍歷字符串,直到找到 x 或 z。 如果未找到 x 或 z,則循環將繼續超過字符串的末尾。 這會導致異常。

我會推薦一個 for 循環:

for(int i = 0; i < lower.length; i++) {
    String letter = lower.substring(i, i + 1);
    if(letter.equals("x") || letter.equals("z")) return true;
} 
return false;

暫無
暫無

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

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