I have written a method that checks if n
number of true
booleans
are present in a boolean[]
array. Then I improved it to var args format which is as follows:
public static boolean checkNTrue(int n, boolean... args) {
assert args.length > 0;
int count = 0;
for( boolean b : args ) {
if(b) count++;
if( count > n )
return false;
}
return ( count == n );
}
I implement it to check if only one of all those boolean
s is true by using:
boolean result = checkNTrue(1, false, true, false, false);
The above returns true
confirming the required case. But what if there are only two boolean
arguments? A simple XOR could return the right result.
And in the case of 3 booleans
, return (a ^ b ^ c) ^ (a && b && c);
works fine too. So, my question is:
Do I need to write separate methods to check in cases with 2 and 3 variables?
Or will this one method do fine? I invite every kind of criticism through downvotes and comments, but please enlighten me! :-)
args.length > 0
? Ifargs
has zero length, why not just returnn == 0
? \$\endgroup\$ – user14393 Mar 15 '14 at 3:49