我正在尝试编写代码来告诉用户他们输入的单词是否是回文。
我正在使用递归方法来反转单词,但它没有正确终止。当StackOverFlowError
我测试它时出现。我的终止代码对我来说看起来是正确的,所以我不确定它为什么不起作用。
此外,当我尝试将String
对象全部设为小写字符时,调试器是否显示该单词全部小写,还是保持不变?
这是代码:
public class Palindrome
{
private String word;
/**
* Constructor for objects of class PalindromeTester
*/
public Palindrome(String supposedPalindrome)
{
word = supposedPalindrome;
}
/**
* Tests if the word is a palindrome or not.
*/
public void testPalindrome()
{
String reversed = reverse();
if(reversed.equals(word.toLowerCase()))
{
System.out.println(word + " is a palindrome!");
}
else
{
System.out.println(word + " is not a palindrome.");
}
}
/**
* Reverses the word.
*
* @return the reversed string.
*/
private String reverse()
{
return reverseHelper(word);
}
/**
* A recursive method that reverses the String for the
* reverse the string method.
*
* @return the reversed string.
*/
private String reverseHelper(String s)
{
s.toLowerCase();
if(s.length() <= 1)
{
return s;
}
else
{
return reverseHelper(s.substring(1, s.length()) + s.charAt(0));
}
}
}
感谢您的帮助!