如何让这段代码发挥作用?我需要返回 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/