[英]Is this a valid Method? Eclipse seems to suggest there is ab issue with my code..I just do not see it
我不知道为什么以下代码被eclpise视为错误。 我一直在“hasPassed()”下面得到一个红色下划线....我一直盯着代码几个小时......
public String hasPassed()
{
if (totalMark ==100 && totalMark > passMark)
return "Pass";
else if (totalMark != 100)
return "There is an error with the mark allocation";
}
您需要添加额外的回报,如果这两个条件是假的,会发生什么?
public String hasPassed()
{
if (totalMark ==100 && totalMark > passMark)
return "Pass";
else if (totalMark != 100)
return "There is an error with the mark allocation";
return "What i have to return"?
}
在这种情况下,IMO更可读重构您的方法,但这是个人的。 像这样的东西。
public String hasPassed(){
String toReturn = null;
if (totalMark ==100 && totalMark > passMark){
toReturn="Pass";
}else if (totalMark != 100){
toReturn= "There is an error with the mark allocation";
}
return toReturn;
}
如果仍有可能满足任何条件,则最终可能没有有效的回报。
试试以下内容:
public String hasPassed()
{
if (totalMark == 100 && totalMark > passMark)
{
return "Pass";
}
else if (totalMark != 100)
{
return "There is an error with the mark allocation";
}
return null;
}
在ifs中始终使用大括号以获得代码清晰度也是一种很好的做法。
这就是为什么总是在方法结束时放置一个返回值的好主意。
public String hasPassed()
{
String message = "Default message";
if (totalMark ==100 && totalMark > passMark)
{
message = "Pass";
} else if (totalMark != 100)
{
message = "There is an error with the mark allocation";
}
return message;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.