[英]Unreachable statement error when trying to return from a while loop - Java
static long minDaysToEmpty(long C, long l) {
long previousFill=C;
long day=1;
long currentFill=C;
while(true){
currentFill=Math.min(C,(previousFill-(day))+l);
previousFill=currentFill;
day++;
if(day>3){
return day;
}
}
return day;
}
This code throws a compile time error.此代码会引发编译时错误。
Test.java:15: error: unreachable statement return day;
I don't understand why this statement can't be reached.我不明白为什么这个声明达不到。
On doing the below modification to the original code, the if block is reachable在对原始代码进行以下修改后,可以访问 if 块
if(day>3){
break;
}
But inside the same block return statement is unreachable.但是在同一个块内返回语句是不可访问的。
Since the while loop is while (true)
and contains no break
statements, the only way the loop can exit is by fulfilling this condition, which is already returning from the method由于 while 循环是
while (true)
且不包含break
语句,因此循环退出的唯一方法是满足此条件,该条件已从方法返回
if (day > 3) {
return day;
}
Therefore the return day
at the bottom of the method is not possible to reach.因此,方法底部的
return day
是不可能到达的。
Just remove that line return day;
只需删除该线路
return day;
at the bottom of the method.在方法的底部。 Provided your logic is correct and
day
will eventually be greater than 3, you don't need it.如果你的逻辑是正确的并且
day
最终会大于 3,你就不需要它。
Alternatively, choose a proper condition rather than while (true)
, or add a break statement.或者,选择一个合适的条件而不是
while (true)
,或者添加一个 break 语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.