What is wrong with my code (Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 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. Infinite loop occur when there is actually no x
or z
in your String
.
StringIndexOutOfBoundsException
occur when i >= lower.length()-1
So you need to modify your while loop to
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
You are looping through the string until x or z is found. If x or z is not found, the loop will continue on past the end of the string. This causes the exception.
I would recommend a for loop:
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.