ユーザーが入力した単語が回文かどうかをユーザーに伝えるコードを作成しようとしています。
単語を逆にするために再帰的な方法を使用していますが、正しく終了しません。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));
}
}
}
ご協力ありがとうございました!