退货声明

时间:2013-09-21 22:11:23

标签: java return

如何让此代码生效?我需要从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;
}

2 个答案:

答案 0 :(得分:1)

我会将你的连接移到条件之后但是在return语句之前:

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;

答案 1 :(得分:0)

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

String robotStatus;
    String robotWall;
    String robotGround;