我试图检查一个单词是否是回文,我正在使用递归,我不知道我做错了什么但是当我到达基本情况时,该方法继续调用最终所有单词返回false.任何人都可以帮我找到错误吗?谢谢 :/
public static void main(String[] args)
{
System.out.print("Enter a word: ");
Scanner sc = new Scanner(System.in);
String isPalindrome = sc.next();
String regex = "[.!? ]";
isPalindrome.split(regex);
if(testPalindrome(isPalindrome)==true)
{
System.out.print(isPalindrome+" is a palindrome.");
}
else
{
System.out.print(isPalindrome+" is not a palindrome.");
}
}
public static boolean testPalindrome(String word)
{
if(word.charAt(0)==word.charAt(word.length()-1))
{
if(word.length()==1)
{
return true;
}
word = word.substring(1, (word.length()-1));
testPalindrome(word);
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
您需要返回递归调用的结果.现在,你递归调用函数是的,但最终,因为你在进行递归调用时没有从函数返回,执行流程离开了外部if语句并移动到return false;即使你递归和递归到某个地方行返回true.
public static boolean testPalindrome(String word)
{
if(word.charAt(0)==word.charAt(word.length()-1))
{
if(word.length()==1)
{
return true;
}
word = word.substring(1, (word.length()-1));
return testPalindrome(word);
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
编辑:superhawk610对你的退出条件也是正确的.它仅对字符串中的奇数个字符有效.您应该使用类似的东西if (word.length() <= 1)来捕捉奇数和偶数情况.这意味着最终代码将是:
public static boolean testPalindrome(String word)
{
if(word.charAt(0)==word.charAt(word.length()-1))
{
if(word.length()<=1)
{
return true;
}
word = word.substring(1, (word.length()-1));
return testPalindrome(word);
}
return false;
}
Run Code Online (Sandbox Code Playgroud)