0

如何使此代码正常工作?我需要从 3 个场景中返回语句,目前我在 String robotInfo 处遇到错误。

String generateStatusReport(Robot robot) {

    String robotStatus;
    String robotWall;
    String robotGround;
    String robotInfo = robotStatus + robotWall + robotGround;

    if(isRobotDead(robot)) {
        robotStatus = ("The robot is dead.");
    } else {
        robotStatus = ("The robot is alive.");
        if(isRobotFacingWall(robot)) {
            robotWall = ("The robot is facing a wall.");
        } else {
            robotWall = ("The robot is not facing a wall.");
        }

        if(isItemOnGroundAtRobot(robot)) {
            robotGround = ("There is an item here.");
        } else {
            robotGround = ("There is no item here.");
        }
    }
    return robotInfo;
}
4

2 回答 2

1

我会将您的串联移动到条件之后但在返回语句之前:

String generateStatusReport(Robot robot) {

    String robotStatus;
    String robotWall;
    String robotGround;

    if(isRobotDead(robot))
        robotStatus = ("The robot is dead.");
    else {
        robotStatus = ("The robot is alive.");
        if(isRobotFacingWall(robot))
            robotWall = ("The robot is facing a wall.");
        else
            robotWall = ("The robot is not facing a wall.");

        if(isItemOnGroundAtRobot(robot))
            robotGround = ("There is an item here.");
        else
            robotGround = ("There is no item here.");
    }
    String robotInfo = robotStatus + robotWall + robotGround;
    return robotInfo;
}

或者只是返回串联:

return robotStatus + robotWall + robotGround;
于 2013-09-21T22:17:51.153 回答
0

您需要初始化您的字符串以获取 robotsInfo 中的值

String robotStatus;
    String robotWall;
    String robotGround;
于 2013-09-21T22:13:13.907 回答