[英]Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
What is wrong with my code (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;
}
}
Your while loop keep looping until x
or z
is found.您的 while 循环不断循环,直到找到
x
或z
。 Infinite loop occur when there is actually no x
or z
in your String
.当您的
String
实际上没有x
或z
时,就会发生无限循环。
StringIndexOutOfBoundsException
occur when i >= lower.length()-1
StringIndexOutOfBoundsException
当i >= lower.length()-1
So you need to modify your while loop to所以你需要修改你的while循环
while (!found && i < lower.length()-1)
Your loop terminating condition only relies on whether character is found or not.您的循环终止条件仅取决于是否找到字符。
while (!found)
Suppose, you don't found anything then you will never do假设,你没有发现任何东西,那么你永远不会做
if(letter.equals("z") || letter.equals("x"))
found=true
and keep on incrementing i
, which will give you StringIndexOutOfBoundsException once it will be equals to string's length并继续增加
i
,一旦它等于字符串的长度,它就会给你 StringIndexOutOfBoundsException
You are looping through the string until x or z is found.您正在遍历字符串,直到找到 x 或 z。 If x or z is not found, the loop will continue on past the end of the string.
如果未找到 x 或 z,则循环将继续超过字符串的末尾。 This causes the exception.
这会导致异常。
I would recommend a for loop:我会推荐一个 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.