不理解遗漏的退货声明

Col*_*ura 0 java

我是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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Mad*_*iha 5

如果email.endsWith(".sc")返回false,则该函数没有return语句.

由于您将返回类型声明为String,因此该函数必须始终返回String(或null).

所以在你的情况下:

if (email.endsWith(".sc")) {
    return email;
}
return null; //Will only reach if condition above fails.
Run Code Online (Sandbox Code Playgroud)