Generally, your naming is good. I never like nums
as a name, but sometimes, like in this case, it's hard to see anything more descriptive. Perhaps just numbers
. no14
is also not a great name, though since this is testing something so specific, there probably aren't many candidates. emptyOfOnesOrFours
or similar might be better, cumbersome as it is.
As for code, the algorithm is a good and clear start, but let's see if we can do any better with the code through refactoring.
First, we can see that there's actually there's actually a lot of the same code being done separately for 1 and 4. Imagine if you added, say, six more numbers to that list, and you'd see a lot of repetition emerging. So the first thing to do would be to extract that into a method:
private boolean contains(int[] numbers, int target) {
int targetCount = 0;
for(int i=0; i<numbers.length; i++) {
if(numbers[i] == target) {
targetCount++
}
}
if(targetCount > 0) {
return false;
}
return true;
}
Now that we've done this, we can see an obvious simplification:
private boolean contains(int[] numbers, int target) {
for(int i=0; i<numbers.length; i++) {
if(numbers[i] == target) {
return true;
}
}
return false;
}
Now our original method can read much clearer:
public boolean emptyOfOnesOrFours(int[] numbers) {
return !contains(numbers,1) || !contains(numbers,4);
}
(That's just about pushing the complexity of what I'd want in a single line, so depending on taste you could separate that out by first assigning the individual contains
calls to booleans.)