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.

+3


source to share


4 answers


There are two problems in the code:

  • array[i] != 1 || array[i] !=4

    will always be evaluated before true

    . 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;
}

      

+8


source


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;
}

      

+4


source


You only check every second element because you are incrementing twice i

.

Remove this line: i++;

You are already incrementing i

in the for loop:for(int i = 0; i < array.length; i++){

+1


source


if (array [i]! = 1 && array [i]! = 4) {or if (! (array [i] = 1 || array [i] = 4)) {

You've managed to link both correct tests that will work and create one that doesn't. Pretty easy to do, so always check for complex boolean expressions.

Good luck :)

0


source







All Articles