问题
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;
}
}
回答1:
You need return isPalindrome();
. Otherwise the method isn't returning anything in that case, and it's declared to return a boolean.
回答2:
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).
回答3:
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();
}
回答4:
your last if clause misses a return, if you really want to return false in the else-clause.
回答5:
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");
}
}
来源:https://stackoverflow.com/questions/18788204/missing-return-statement-error-in-java