Java – try to create a method to check whether the array contains only 1 or 4

static boolean checkNum(int[] array) {
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 tried several codes, but I didn't have any luck What should I do? It just needs to go through the array and find anything that is not 1 or 4, otherwise it should be true

Solution

There are two problems in your code:

> array [i]!= 1 || array [i]!= 4 will always be evaluated as true No number is 1 or 4

You are looking for condition array [i]= 1&& array [i]!= 4 means "the number is not 1, not 4" Another effective alternative is! (array [i] = = 1 | array [i] = = 4), which means "the number is not 1 or 4" Which one you finally choose depends on your personal preferences. > As others have pointed out, I in the loop is redundant and causes the loop to skip every element

This version should solve your problem:

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 any possibility other than the variable bool?

Bonus: if you use the foreach loop instead of the for loop, it's clearer:

static boolean checkNum(int[] array) {

    for (int i : array) {

        if (i != 1 && i != 4) {
            return false;
        }

    }

    return true;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>