Reputation: 11
I'm trying to write a function that checks whether a string variable is a palindrome or not.
I can't find the reason this code throws IndexOutOfBoundException
. I've tried to use examples so as to follow the result, but I still can't see where the exception is from.
public static boolean palindrome(String s) {
if (s.charAt(0) == s.charAt(s.length() - 1)) {
if (s.length() > 2) {
StdOut.print(s.substring(1, s.length() - 2));
palindrome(s.substring(1, s.length() - 2));
} else
return true;
}
return false;
}
Upvotes: 1
Views: 141
Reputation: 30136
Try this:
public static boolean palindrome(String s)
{
if (s.length() < 2)
return true;
if (s.charAt(0) != s.charAt(s.length()-1))
return false;
return palindrome(s.substring(1,s.length()-1));
}
Upvotes: 2
Reputation: 311188
There are several problems here:
substring
call is wrong - the endIndex
is exclusive, so you should end at s.length() - 1)
palindrome
, and then moving on with the function, eventually returning false
- instead, you should return the result of palindrome
applied on the substring:So, after taking both these mistakes in to considetation, the method should read as follows:
public static boolean palindrome(String s) {
if (s.charAt(0) == s.charAt(s.length() - 1)) {
if (s.length() > 2) {
// note the return and the corrected substring
return palindrome(s.substring(1, s.length() - 1));
} else
return true;
}
return false;
}
Upvotes: 1
Reputation: 393781
Your substring is wrong. You are removing an extra character from the end.
public static boolean palindrome(String s) {
if (s.charAt(0) == s.charAt(s.length() - 1)) {
if (s.length() > 2) {
StdOut.print(s.substring(1, s.length() - 1));
palindrome(s.substring(1, s.length() - 1));
} else
return true;
}
return false;
}
Upvotes: 1
Reputation: 500287
palindrome
can end up calling itself with an empty string. When that happens, the first line with give an IndexOutOfBoundsException
in s.charAt(0)
.
P.S. On closer inspection, the bounds in the substring
calls are also incorrect: since the end index is exclusive, the second argument should be s.length() - 1
. You'll need to fix that too.
Upvotes: 4