Trying to create a method to check if an array only contains 1 or 4
static boolean checkNum(int[] array) {
boolean bool = true;
for (int i = 0; i < array.length; i++) {
if (array[i] != 1 || array[i] != 4) {
return !bool;
}
i++;
}
return bool;
}
I've tried coding this in multiple ways but haven't had any luck. How am I supposed to do this? it just needs to go through the array and find anything that is not 1 or 4, otherwise it should be true.
source to share
There are two problems in the code:
-
array[i] != 1 || array[i] !=4
will always be evaluated beforetrue
. Any number is not equal to 1 or not 4.You're looking for a condition
array[i] != 1 && array[i] !=4
that says "number is not 1, not 4". Another valid alternative would be!(array[i] == 1 || array[i] == 4)
one that says "The number is not equal to 1 or 4." Which one you finish depends on your personal preference. - As others have pointed out,
i++
inside the loop is redundant and causes the loop to skip every other element.
This version should fix your problems:
static boolean checkNum(int[] array) {
for (int i = 0; i < array.length; i++) {
if (array[i] != 1 && array[i] != 4) {
return false;
}
}
return true;
}
Do you see how it was possible to get rid of the variable bool
?
Bonus: It's even clearer if you use a forEach loop instead of a for loop:
static boolean checkNum(int[] array) {
for (int i : array) {
if (i != 1 && i != 4) {
return false;
}
}
return true;
}
source to share
Logically, if the value at the current position is not equal to 1 and not equal to 4, then return false.
static boolean checkNum(int[] array){
for(int i = 0; i < array.length; i++){
if(array[i] != 1 && array[i] != 4){
return false;
}
}
return true;
}
I would also recommend a for-each
loop like
static boolean checkNum(int[] array){
for(int val : array){
if (val != 1 && val != 4){
return false;
}
}
return true;
}
source to share