When I typed in the following method and compiled it in Java, I got "error: unreachable statement", why ?
String getRankChar(int rank,boolean isFront)
{
switch (rank)
{
case 0 : return isFront?"<":">";break;
case 1 : return isFront?"[":"]";break;
case 2 : return isFront?"[":"]";break;
case 3 : return isFront?"(":")";break;
case 4 : return isFront?"(":")";break;
default : return " ";break;
}
}
You've got a break
statement after each return
statement. All those break
statements are unreachable, precisely because you return before each of them.
As per section 14.21 of the JLS:
It is a compile-time error if a statement cannot be executed because it is unreachable.
And:
[...] Every other statement S in a non-empty block that is not a switch block is reachable iff the statement preceding S can complete normally.
...
A
break
,continue
,return
, orthrow
statement cannot complete normally.
The return
statement cannot complete normally, so the break
statement is unreachable (for each of your cases).
Just remove the break
statements and it'll be fine.
See more on this question at Stackoverflow