Reputation: 213
public static String check(String str)
{
String result = "";
// Strips the string down to only letters a-z and numbers 0-9, and makes it lowercase
str = str.replaceAll("[^A-Za-z0-9]", "");
str = str.replaceAll("\\s+","");
str = str.toLowerCase();
if (str.length() < 1)
{
result = "The string is a palindrome";
}
else if ((str.charAt(str.length() - 1)) == (str.charAt(0)))
{
StringBuilder sb = new StringBuilder(str);
sb.deleteCharAt(0);
sb.deleteCharAt(sb.length()-1);
check(sb.toString());
}
else
{
result = "The string is not a palindrome";
}
return result;
}
I tried passing several strings into this method, including palindromes. For some reason, it keeps returning the default value of "". Why won't the method return information about whether or not the string is a palindrome?
Upvotes: 2
Views: 49
Reputation: 188
You have to add return before recursive calling. Try this way:
public static String check(String str)
{
// Strips the string down to only letters a-z and numbers 0-9, and makes it lowercase
str = str.replaceAll("[^A-Za-z0-9]", "");
str = str.replaceAll("\\s+","");
str = str.toLowerCase();
if (str.length() <= 1)
{
return ("The string is a palindrome" );
}
else if ((str.charAt(str.length() - 1)) == (str.charAt(0)))
{
StringBuilder sb = new StringBuilder(str);
sb.deleteCharAt(0);
sb.deleteCharAt(sb.length()-1);
return check(sb.toString());
}
else
{
return "The string is not a palindrome";
}
}
Upvotes: 3