An application have 5 checkboxes as input, which means there are 32 possible combinations of input. There is an action associated with each combination of user inputs. Assume that each conditional statement (for e.g. each case in the switch statement or each if or else statement) takes 1 second and each action takes 1 second. The simplest solution is to write 32 conditional statements to cover all the possible combination of inputs but this is not optimised. Write an application such that the selected action will be executed within 7 seconds from user input.

解决方案 »

  1.   

    实际上,这五个checkbox可以组成一个五层深的二叉树,每一个节点都是对一个checkbox的真假判断,
    这样,完成五个checkbox的判断只需要5秒,
    最后1秒执行动作,共6秒。按照以上思路,实现上比较笨的办法是硬写if..else语句组合:
    if (checkbox1.selected){
      if (checkbox2.selected){
       ...
      }else{
       ...
      }
    }else{
      if (checkbox2.selected){
       ...
      }else{
       ...
      }
    }---------------还有一种思路,我觉得2秒就可以搞定:
    1、将5个checkbox当作5个bit位组织成一个整数,最大32
    2、建立一个32长度的数组,存放要执行的action
    3、直接拿第一步得到的整数去数组中定位action执行即可,具体技术可以考虑reflection等。
      

  2.   

    完全不用判断,利用java的反射机制可以很好的解决
    我举了一个小例子,不知道是否满足你的要求import java.lang.reflect.Method;
    import java.util.HashMap;
    import java.util.Map;public class Application { public static void main(String[] args) throws Exception {
    //初始化,每个分支对应一个action:[0:action0, 1:action1, ..., 31:action31]
    Map<Integer, String> map = new HashMap<Integer, String>();
    map.put(0, "action0");
    map.put(1, "action1");
    map.put(2, "action2");

    //五位数代表五个checkbox; 状态:[1:选中; 0:未选中]
    String checked = "00010"; 

    //根据checkbox选择状态直接获取分支
    int combination = Integer.valueOf(checked, 2); //利用反射
    Method method = Application.class.getMethod(map.get(combination), null);
    Object obj = method.invoke(new Application(), null);

    }

    public void action0() {
    System.out.println("action0 excuted....");
    }
    public void action1() {
    System.out.println("action1 excuted....");
    }
    public void action2() {
    System.out.println("action2 excuted....");
    }
    /*
     * actionN......
     */
    }