在我的教科书中提到,只要你想立即结束一个void方法,你就可以引入return;但是,我尝试在 eclipse 上实现它,但它似乎不起作用。我试图在可变日期结束该方法。我收到一条错误消息,指出我的其余代码无法访问。
public void readInput(){
Scanner myKeyboard = new Scanner(System.in);
System.out.println("Enter the day");
day = myKeyboard.nextInt();
return; //error is here
System.out.println("Enter the year");
year = myKeyboard.nextInt();
System.out.println("Enter the month");
month = myKeyboard.next();
}
有没有我的教科书忘记提到的东西!?
最佳答案
在 Java 中,it's illegal to include code that can't ever possibly be executed (因为这几乎总是一个错误)。在您的代码中,您无条件地调用了 return
,之后您有额外的代码——这称为 unreachable code,它会导致编译器错误。
在方法中间使用return
是为了当你有条件的时候,比如
if(exitNow) {
return;
}
否则程序可能会继续执行剩余的代码。要对此进行测试,请尝试以下操作:
if(day == 0) {
return;
}
正如@fdreger 提到的,JLS 特别指出,即使 if
语句的条件是编译时常量,编译器也会将 if
视为条件不确定(这仅适用于 if
,不适用于 do
、while
或 for
循环),所以这将使您的代码编译:
if(true) {
return;
}
关于java - 以 return 结束 void 方法;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19778014/