• if语句的数据驱动优化(Java版)


    举个栗子,如果我要输出数字对应的中文描述,我可以用这种方法来写:

    int num=2;
    
    if (num==1){
        System.out.println("一");
    }
    else if (num==2){
        System.out.println("二");
    }
    else if (num==3){
        System.out.println("三");
    }
    else if (num==4){
        System.out.println("四");
    }
    else if (num==5){
        System.out.println("五");
    }else {
        System.out.println("其它");
    }

    但是如果有一百个数字,难道你要写一百次的if语句么??所以可以优化成下面这样的表驱动:

    public static String ConvertNumber(int num){
        Map<Integer,String> map=new HashMap<Integer,String>();
        map.put(1,"一");
        map.put(2,"二");
        map.put(3,"三");
        map.put(4,"四");
        map.put(5,"五");
        for (Integer integer:map.keySet()){
            if (integer==num){
                return map.get(integer);
            }
        }
        return "其它";
    }

    然后在Main函数中直接调用该方法System.out.println(ConvertNumber(num));就可以啦!

    显而易见的是,第二种数据驱动的编程方式更为简练,它将数据和逻辑剥离,拓展性好。

    比如我想添加一个6对应的六,只要在代码的数据段中添加map.put(6,"六");就可以了。

  • 相关阅读:
    字符数组与指针
    终于在博客园安家了
    关于SET NOCOUNT
    如何判断请求是否发送成功以及获取请求中的数据
    mysql进阶 withas 性能调优
    Linux mkdir
    Linux umask and chmod
    C linux Debug
    Linux sed
    Linux ulimit
  • 原文地址:https://www.cnblogs.com/chenyangsocool/p/9054862.html
Copyright © 2020-2023  润新知