if-statement - 在没有 if 语句的情况下做出决定
问题描述
我想将此代码转换为另一个没有 switch 或 if 语句的代码。
请问有什么帮助吗?
这是一个工作面试问题
if(x==9)
return "3";
if (x==3)
return "9";
else
return "not valid";
其中 x 是用户输入
解决方案
你考虑过三元吗?
String result = x == 9 ? "3" : "not valid";
result = x == 3 ? "9" : result;
return result;
还是带有三元的地图?
Map<Integer, String> map = new HashMap<>();
map.put(9, "3");
map.put(3, "9");
String result = map.get(x);
return result == null ? "not valid" : result;
推荐阅读
- angular - 在将整个数据加载到 Angular 之前,如何显示 ngx-spinner
- copy - 将过滤后的行从一个 google 工作表批量复制到另一个 google 工作表
- coinbase-api - 使用比特币地址发送 off_blockchain 交易(即时发送)
- firebase - 在 firebase 实时数据库中进行更复杂验证的最佳方法是什么?
- javascript - 如何在浏览器中自动弹出 acrobat 阅读器?(项目中使用javascript、nodejs、codeceptjs)
- bash - 您如何为多个程序定义相同的自动完成功能?
- assembly - OllyDbg - 如何向 .exe 文件添加更多指令空间?
- flutter - flutter web TypeError: dart.global.firebase.storage 不是函数
- asp.net-mvc - 如何将 Azure Relay 和 MVC 与 auth 一起使用,并且仍然可以查看 Swagger 文档 URL?
- automated-tests - sendKeys() 不传递字符“@”