返回语句不停止代码java
我想检查一个单词是否是回文,我正在使用递归,我不知道我在做什么错,但是当我到达基本情况时,该方法一直调用最终所有字返回错误。任何人都可以帮我找到错误吗?谢谢:/返回语句不停止代码java
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;
}
您需要返回递归调用的结果。现在,您可以递归调用函数yes,但最终,因为在进行递归调用时不会从函数返回,所以执行流将离开该外部语句并移至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;
}
编辑: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;
}
假设你并不需要检查在true
如果作为该方法返回一个boolean
System.out.print("Enter a word: ");
Scanner sc = new Scanner(System.in);
String isPalindrome = sc.next();
String regex = "[.!? ]";
isPalindrome.split(regex);
if(testPalindrome(isPalindrome))
{
System.out.print(isPalindrome+" is a palindrome.");
}
else
{
System.out.print(isPalindrome+" is not a palindrome.");
}
也testPalindrome()
方法应该是这样的递归工作。
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;
}
非常感谢。 :D – noobProgrammer
@noobProgrammer欢迎。 –
这看起来像它可以处理奇数长度的单词,但不能处理长度均匀的单词。更改测试的语句从
if(word.length() == 1)
到
if(word.length() < 2)
这将结束递归,如果你已经下调到1个字符(奇数长字的中间)或0(的“中间”一个均匀长度的词)。
:| |我怎么错过了? :/非常感谢:D – noobProgrammer
现在假设答案更准确。 –