1

这是我的问题。我有三个布尔值,这是我可以拥有的选项。我可以使用三个选项进行多种组合:

即没有选项(全部为假) 选项 1 仅选项 1 和选项 2 选项 1 和选项 2 和选项 3 选项 2 仅选项 2 和选项 3 选项 3 等

我需要检查所有组合,但我不想编写大量 if else if 语句。

有没有办法可以获得结果应该是什么?

就像是

result = option1 & option2 & option3

然后我可以进入一个 switch 语句来处理正确的组合

如果您需要更详细的解释,请告诉我。提前致谢。

ps 我在这里要做的是避免有这么多的 if else if 语句,并使我的代码看起来更干净,设计得更好。因此,如果您能想到另一种方法,我将不胜感激。

谢谢

4

3 回答 3

2

您可以为每个可能的结果生成一个Karnaugh_map,使用它的规则,您可以简单地将一组特定条件的逻辑降至最低。

但是我认为最好是为了清楚起见,尝试遵循逻辑流程来了解为什么采用某些分支。如果它太令人费解,也许重新考虑情况是有道理的。

于 2011-06-21T18:44:49.083 回答
1

以下是在 switch 中获取所有 8 个案例的一种方法。

将布尔值转换为不同的 int 标志(仅设置一位的值),将它们与按位 OR 组合,然后打开 8 个可能的值。

int combination = (option1 ? 1 : 0) | (option2 ? 2 : 0) | (option3 ? : 4 : 0);

switch(combination) {
case 0: // !1 && !2 && !3
  ...
break;
case 1: // 1 && !2 && !3
  ...
break;
case 2: // !1 && 2 && !3
  ...
break;
case 3: // 1 && 2 && !3
  ...
break;
case 4: // !1 && !2 && 3
  ...
break;
case 5: // 1 && !2 && 3
  ...
break;
case 6: // !1 && 2 && 3
  ...
break;
case 7: // 1 && 2 && 3
  ...
break;
}

使用这种方法,您可以平等地处理所有 8 种情况。但是,如果添加更多布尔值,它将变得失控,因为组合的数量呈指数增长。

于 2011-06-21T21:14:57.560 回答
0

我的解决方案不适用于布尔值,但您可以调整它。例如调用 Option.CombinedOption.get(Option.ONE, Option.THREE) 返回枚举 CombinedOption.OPTION_1_3。

public enum Option {
ONE, TWO, THREE;

public enum CombinedOption {

    ALL_FASLSE(), OPTION_1(ONE), OPTION_1_2(ONE, TWO), OPTION_1_3(ONE,
            THREE), OPTION_1_2_3(ONE, TWO, THREE), OPTION_2(TWO), OPTION_2_3(
            TWO, THREE), OPTION_3(THREE);

    private Set<Option> keySet;

    private CombinedOption(Option... options) {
        if (options != null && options.length > 0)
            keySet = EnumSet.copyOf(Arrays.asList(options));
        else
            keySet = EnumSet.noneOf(Option.class);

    }

    private static final Map<Set<Option>, CombinedOption> optionMapping = new HashMap<Set<Option>, CombinedOption>();

    static {
        for (CombinedOption combined : CombinedOption.values()) {
            optionMapping.put(combined.keySet, combined);
        }
    }

    public static CombinedOption get(Option... options) {
        Set<Option> keySet;

        if (options != null && options.length > 0)
            keySet = EnumSet.copyOf(Arrays.asList(options));
        else
            keySet = EnumSet.noneOf(Option.class);

        return optionMapping.get(keySet);
    }
}

}

于 2011-06-21T20:55:09.583 回答