我目前正在用Java编写一个回文测试器,用于我在高中学习的课程。我已经向老师求助了,他也很困惑。我希望stackoverflow上的社区可以帮助我。谢谢。
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;
}
}
答案 0 :(得分:7)
您需要return isPalindrome();
。否则该方法在这种情况下不返回任何内容,并且声明它返回一个布尔值。
答案 1 :(得分:3)
更改
if (sentence.charAt(0) == sentence.charAt(sentence.length()-1))
{
sentence = sentence.substring(1, sentence.length()-1);
isPalindrome();
}
到
if (sentence.charAt(0) == sentence.charAt(sentence.length()-1))
{
sentence = sentence.substring(1, sentence.length()-1);
return isPalindrome();
}
为了使方法得到遵守,JVM需要确保该方法对每种可能的情况都有一个return语句(这是你没有做过的事情)。
答案 2 :(得分:2)
如果您的代码采用此路径,则没有return语句。如果您的老师感到困惑,您需要一位新老师。
if(sentence.charAt(0) == sentence.charAt(sentence.length()-1))
{
sentence = sentence.substring(1, sentence.length()-1);
isPalindrome();
}
答案 3 :(得分:0)
如果你真的想在else子句中返回false,你的最后一个if子句会错过一个返回。
答案 4 :(得分:0)
您想使用递归方式检查句子是否是回文。你最好在以下代码片段
中返回isPalindrome()方法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");
}
}
这是我的代码:
Field1 | Field2
A | 1
B | 1
C | 2
D | 2
B | 3
O | 3
L | 3