Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

java - How do you make a conditional statement return true when only one condition is true?

I need to make an if statement in which its value depends on N other conditions. Particularly, it needs to return true only when one of N conditions are true (if more than one condition is true, it has to return false). More formally, if (1, 2, 3 ... N) should evaluate true if and only if only one of the statements evaluates true, otherwise evaluates false.

I implemented this method,

boolean trueOnce(boolean[] conditions) {

    boolean trueOnce = false;

    for (boolean condition : conditions) {
        if (condition) {
            if (!trueOnce) {
                trueOnce = true;
            } else {
                trueOnce = false;
                break;
            }
        }
    }

    return trueOnce;
}

but I'm asking for something more practical. I'm working with Java, but I think this problem is universal for every language. Thanks.

EDIT: this method does the job very well, but my question is, does Java (or any other language) have a more practical way of doing this (that is, without even implementing a whole method)?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you could use this solution

public boolean trueOnce(boolean[] conditions) {
         boolean m = false;
         for(boolean condition : conditions) {
             if(m && condition)
                 return false;
             m |= condition;
         }
         return m;
     }

this is a very small solution that does exactly what you want in very few lines.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...