java - 返回声明

标签 java return

如何让这段代码发挥作用?我需要返回 3 个场景的语句,目前我在 String robotsInfo 处收到错误。

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;
}

最佳答案

我会将您的串联移至条件之后但 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;

关于java - 返回声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18938201/

相关文章:

javascript - 为什么数组的长度没有显示在浏览器中?

c - 了解 C 中的字符串赋值

java - Wicket 口 6 : Including Javascript files to head with script tag

java - Spring 启动 : What is the Right Way to Implement Basic Auth with httpheaders

python - 从函数返回多个值的最佳方法?

javascript - 如何仅在回调完成时返回

php - 函数只返回一个元素

java - 将日期作为存储过程中的参数传递(oracle)

java - Hibernate 中的分布式查询缓存

java - 使用 JMS 作为请求/响应服务