[英]Missing return statement error in Java
我目前正在为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;
}
}
您需要return isPalindrome();
。 否则,在这种情况下该方法将不会返回任何内容,并且将其声明为返回布尔值。
更改
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语句(这是您尚未完成的事情)。
如果您的代码采用此路径,则没有return语句。 如果您的老师感到困惑,您需要一位新老师。
if(sentence.charAt(0) == sentence.charAt(sentence.length()-1))
{
sentence = sentence.substring(1, sentence.length()-1);
isPalindrome();
}
如果您真的想在else子句中返回false,则您的最后一个if子句会错过返回。
您想使用递归方法来检查句子是否为回文。 您最好在以下代码段内返回isPalindrome()方法
if(sentence.charAt(0) == sentence.charAt(sentence.length()-1))
{
sentence = sentence.substring(1, sentence.length()-1);
return 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");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.