不理解遗漏的退货声明
我是Java新手。 我正在进行一个小程序练习并且缺少return语句错误。
有人可以帮忙吗?
import java.util.Scanner; class nonstatic1 { public static void main(String[] args) { // this method works nonstatic2 Ref=new nonstatic2(); int Addition=Ref.add(); System.out.println (Addition); String email=email(); } // the one below is the one that does not work and gives me the error public static String email() { Scanner in=new Scanner(System.in); System.out.println("Enter Your email Address"); String email=in.nextLine(); if(email.endsWith(".sc")) return email; } }
问题出在IF
声明中。 你错过了else
分支。 当表达式的求值为false
,程序不返回任何内容,因此missing return statement
错误。
将其更改为以下内容:
if(email.endsWith(".sc")) return email; else return "invalid email";
如果email.endsWith(".sc")
返回false,则该函数没有return语句。
由于您将返回类型声明为String
,因此该函数必须始终返回String(或null)。
所以在你的情况下:
if (email.endsWith(".sc")) { return email; } return null; //Will only reach if condition above fails.
if(email.endsWith(".sc")) return email;
您的代码不完整。 你确实有一个return
语句,但只有在一种情况下才存在许多情况。
if(email.endsWith(".sc")) { return email; } return null;
这将在逻辑现在完成并且涵盖所有可能性时起作用。
你的function方法
public static String email ()
声明String
类型的返回值。 所以你必须在所有情况下返回一个值。
在函数体中,您只是作为if
的结果调用return
。 在else
情况下,不会调用return
语句。 因此,当if
为false时,您需要添加另一个return
值。
如果您不希望您的方法返回某些内容,以防用户输入无效数据,请执行以下操作:
public static String email() { Scanner in=new Scanner(System.in); System.out.println("Enter Your email Address"); String email=in.nextLine(); if(email.endsWith(".sc")) return email; throw new RuntimeException("Dude, enter normal email man!!!"); }
但是你的方法应该涵盖所有情况,并且总是带有回报或exception!
问题是编译器在您的方法中检测到无法访问return语句的代码路径。 特别是如果(email.endsWith(".sc")
返回false,那么您的方法将无法到达return email;
要解决问题,您可以在方法结束时添加return null;
或者return "";