I am currently writing a palindrome tester in Java for a class I am taking in high school. I have asked my teacher for assistance and he is also confused as well. I was hoping the community on stackoverflow could help me out. Thank you.
public class Palindrome
{
private String sentence;
public Palindrome(String s)
{
sentence = s;
}
public boolean isPalindrome()
{
if(sentence.length() <= 1)
{
return true;
}
if(sentence.charAt(0) == sentence.charAt(sentence.length()-1))
{
sentence = sentence.substring(1, sentence.length()-1);
isPalindrome();
}
else
return false;
}
}
You need return isPalindrome();
. Otherwise the method isn't returning anything in that case, and it's declared to return a boolean.
Change
if (sentence.charAt(0) == sentence.charAt(sentence.length()-1))
{
sentence = sentence.substring(1, sentence.length()-1);
isPalindrome();
}
to
if (sentence.charAt(0) == sentence.charAt(sentence.length()-1))
{
sentence = sentence.substring(1, sentence.length()-1);
return isPalindrome();
}
In order to have the method complied, JVM need to make sure the method has a return statement for every possible case (which is something you haven't done).
If your code takes this path there is no return statement. If your teacher is confused, you need a new teacher.
if(sentence.charAt(0) == sentence.charAt(sentence.length()-1))
{
sentence = sentence.substring(1, sentence.length()-1);
isPalindrome();
}
如果您真的想在else子句中返回false,则您的最后一个if子句会错过返回。
You want to use a recursive way to check if the sentence is palindrome. you'd better to return isPalindrome() method inside following snippet
if(sentence.charAt(0) == sentence.charAt(sentence.length()-1))
{
sentence = sentence.substring(1, sentence.length()-1);
return isPalindrome();
}
This is my code:
public class palindrome
{
private String sentence;
public palindrome(String s)
{
sentence = s;
}
public boolean isPalindrome()
{
if(sentence.length() <= 1)
{
return true;
}
if(sentence.charAt(0) == sentence.charAt(sentence.length()-1))
{
sentence = sentence.substring(1, sentence.length()-1);
return isPalindrome();
}
else
return false;
}
public static void main(String [] args)
{
palindrome p=new palindrome("aabbaa");
if(p.isPalindrome())
System.out.println("yes");
else
System.out.println("no");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.