不用if或者switch 完成以下

不允许使用if或者switch语句 完成下列 在最后一行中输出结果

img

试试三目运算符

写了一份Java版本的

  1. 用了正则表达式判断算式,获取A和B的值以及运算符
  2. 又用了map的key-value键值对,提前将A、B的加减结果存入,乘除的结果更改为error
  3. 根据第一步取得的运算符在map中取出对应值

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

    public static void main(String[] args){
        calculator("12   - 1888");
    }

    public static void calculator(String str){
        String pattern = "(\\d*)(\\s*)(.)(\\s*)(\\d*)";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(str);

        m.find();
        Integer a = Integer.valueOf(m.group(1));
        Integer b = Integer.valueOf(m.group(5));
        String arith = m.group(3);

        HashMap<String,String> map = new HashMap<>();
        map.put("+", Integer.toString(a+b));
        map.put("-", Integer.toString(a-b));
        map.put("*", "error");
        map.put("/", "error");
        System.out.println(map.get(arith));
    }
}