Exception in thread "main" java.lang.StringIndexOutOfBoundsException: Index 6 out of bounds for length 6
Process finished with exit code 1
public class Main {
boolean palindrome(String str, int start, int end){
if(start >= end)
return true;
return(str.charAt(start) == str.charAt(end)) && palindrome(str, start 1, end-1);
}
public static void main(String[] args) {
String str = "aabbaa";
int n = str.length();
System.out.println(palindrome(str, 0, n));
}
}
CodePudding user response:
pay attention to the difference between the index and the length. It's 2 different things.
CodePudding user response:
String's length()
function returns the "real" length of the string, so if you used six letters, it would return 6. However, in programming we start indexing at 0, that means the 6th letter of the word would be indexed as 5.
When you call your palindrome()
method with the value of 6 as the end
parameter, you are telling the code to find the letter with the index of 6, which your string does not have, as the last letter would be indexed as 5 in your case.
You should use line.length() - 1
when using indexes.
Read more: java.lang.StringIndexOutOfBoundsException?