Search code examples
javabooleanboolean-logicboolean-operations

Is there a convenient way to check if at least a certain number of conditions are true?


Is there an easy way to check if a minimum number of conditions have been met? Like, let's say that I've asked somebody to pick at least 4 days of the week. Is there some sort of way that I can check that they've picked at least 4 days? It'd be a real pain to write out all the ands and ors for the possible conditions. Maybe this could be done in java with like a switch statement, but in general is there a straightforward way?

I was thinking it'd be easiest to add up the value of all the boolean statements, and then see if they sum to at least 4. Some pseudo code to demonstrate what I mean:

if ((input.contains("mon") + input.contains("tues") + ... + input.contains("sun")) >=4){
    //do stuff
}

But I'm not sure if that's really a valid way to do it? Help?


Solution

  • Just define a simple method to count the total number of days selected:

    private boolean moreThanFourSelected(input) {
        String days[] = { "mon", "tues", ..., "sun" };
        int total = 0;
        for (String day : days) {
            if (input.contains(day)) total++;
        }
        return total >= 4;
    }