Unreachable Statement Error

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Alexei12
    New Member
    • Apr 2014
    • 1

    Unreachable Statement Error

    Hello,

    I'm new to this, but I am doing Programming, as one of my papers for uni
    And also, I am new to Java and Programming

    But after I compile it, it says 'unreachable statement'


    String generateStatusR eport(Robot karel) {
    Code:
    if(isRobotDead(karel))
        return"The robot is dead." 
    else
        return"The robot is alive.";
    
    if(isRobotFacingWall(karel))  //unreachable statement
        return"The robot is facing a wall.";
    else
        return"The robot is not facing a wall.";
    
    if(isItemOnGroundAtRobot(karel)) //unreachable statement
        return"There is an item here.";
    else
        return"There is no item here.";

    For the return statements, it still works with or without the brackets ( )
    But I get an error message, especially on the second and third if statement

    I don't know why I get an error message saying 'unreachable statement'
    I can't see what the problem/mistake is, that I can see
    NB: Numbers 1-14 is all code
    Last edited by Alexei12; Apr 25 '14, 06:03 AM. Reason: Just needed to take a few parts out
  • chaarmann
    Recognized Expert Contributor
    • Nov 2007
    • 785

    #2
    If you have an if-else statement, and in both cases you return from the method (line 2 and 4 in the listing above), then of course the code below the if-else statement (starting at line 6)) will never be executed.
    The warning from the compiler tells you that you should rethink your program logic (or just delete the unreachable code).

    Remark:
    Some people already have implemented their own Boolean that can have three possible values instead of two: TRUE, FALSE and FILE_NOT_FOUND (or similar). I've seen such implementations . But please do no reinvent bad code.

    Comment

    Working...