2

I have 5 boolean variables a,b,c,d and e. So for each different combination of true and false of each variable there is a different print statement.

Say for example:

a b c d e --- Print Statements

T T T T T -- Print All trues

T T T T F -- Print Some Text

T T T F F -- Print Some other text

........

There could be 32 different possible combinations. I'm writing a java code. So the question is for every condition there should be a different statement printed out. So what could be the best possible solution to handle this instead of the regular if statements which makes the code more confusing and unmanageable?

4

3 に答える 3

9

One option would be to basically build a bitmask:

int mask = (a ? 1 : 0) |
           (b ? 2 : 0) |
           (c ? 4 : 0) |
           (d ? 8 : 0) |
           (e ? 16 : 0);

System.out.println(statements[mask]);

... where statements is an array of length 32. So in your case, statements[31] would be "All trues", and statements[30] would be "Some Text" etc.

于 2013-01-23T18:30:08.927 に答える
1

Interpret true as bit set and false as bit not set. This way you can map all combinations to the int values 0 .. 31.

Than simply define

String[] outputs = new String[32]{"text 1", "text2", ... ,  "text 31"};

and than print outputs[bitconstallation]

于 2013-01-23T18:30:22.303 に答える
1

Why not generalize your bitmask function to pass any arbitrary number of booleans (problably using BigDecimal would be better -> up to specific needs):

/**
* Gets all the boolean combinations in the array of booleans.
* 
* @param booleans
* @return
*/
public static int getBooleanCombinations(final boolean... booleans) {
   int res = 0;
   for (int n = 0; n < booleans.length; n++) {
            final double pow = Math.pow(2, n);
            final boolean bool = booleans[n];
            final Double localres = Double.valueOf(bool ? pow : 0);
            res = localres.intValue() | res;
    }
    return res;
}
于 2014-11-14T10:33:09.387 に答える