首页 > 解决方案 > 这将是一个 if 语句

问题描述

private String adjustDirection(String direction) {

        return (currentFloor == Building.FLOORS)
                ? "down"
                : ((currentFloor == 1) ? "up" : direction);
    }

嗨,我很难理解这个,有什么更简单的写法?

标签: java

解决方案


“三元运算符”基本上是 的简写if-then-else,在这种情况下是嵌套的if-then-else,但您实际上可以通过返回来快捷方式:

private String adjustDirection(String direction) {
    if ( currentFloor == Building.FLOORS) return "down";
    if ( currentFloor == 1) return "up";
    return direction;
}

但是,如果您碰巧受“单次退货”政策的约束,您也可以使用 if/elseif:

private String adjustDirection(String direction) {
    string returnValue = direction;
    if ( currentFloor == Building.FLOORS){
       returnValue = "down";
    }
    else if ( currentFloor == 1) { 
       returnValue = "up";
    }

    return returnValue;
}

速记的“字面”展开将是:

private String adjustDirection(String direction) {
    string returnValue;
    if ( currentFloor == Building.FLOORS){
       returnValue = "down";
    }
    else {
       if ( currentFloor == 1) {
          returnValue = "up";
       }
       else {
          returnValue = direction;
       }
    }
    return returnValue;
}

推荐阅读