java - 这将是一个 if 语句
问题描述
private String adjustDirection(String direction) {
return (currentFloor == Building.FLOORS)
? "down"
: ((currentFloor == 1) ? "up" : direction);
}
嗨,我很难理解这个,有什么更简单的写法?
解决方案
“三元运算符”基本上是 的简写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;
}
推荐阅读
- c# - 使用 entityframework 到 postgresql 运行 linq 查询期间超时
- c# - 如果测试失败,C#/Selenium 重试
- c# - 反序列化存在于不同位置的 xml 配置文件
- wordpress - 在 wp_nav_walker 菜单 WordPress 中显示菜单标签两次
- .net - 是否可以在 Azure 通信服务中的聊天与同一组中发起呼叫
- visual-studio-code - 脚本在 jupyter notebook 中运行,但不在 vscode 中
- database - 如何在 Postgres 中将所有没有模式的数据从一个数据库复制到另一个数据库?
- storage - Azure 逻辑应用中的存储方法
- dynamics-crm - 电子邮件实体上的 Dynamics CRM 安全角色权限
- amazon-web-services - 在 64 位 Amazon Linux 2/3.1.2 平台上运行的 Elastic Beanstalk Ruby 2.6 更新错误:工作人员提前终止