首页 > 解决方案 > 在没有 if 语句的情况下做出决定

问题描述

我想将此代码转换为另一个没有 switch 或 if 语句的代码。

请问有什么帮助吗?

这是一个工作面试问题

if(x==9)
return "3";
if (x==3)
return "9";
else
return "not valid";

其中 x 是用户输入

标签: if-statement

解决方案


你考虑过三元吗?

    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;

推荐阅读