Home > database >  checking for a specific number in a specific order with arrays and condition checks
checking for a specific number in a specific order with arrays and condition checks

Time:10-31

what i'm trying to do is to check if 2 is before 4 in a array i used a for loop and condition check and i see that i'm going wrong in my first condition check. i want to make it so that if two is not in the loop it just breaks and if it sees that four is before it breaks as well.

i put the print statement to see where i was going wrong and it seems to if(array[i] == two and it goes to the else and breaks. i also read that you can do it with another array but that sound off so i also wanted to ask if that was possible.

public static void main(String[] args) {
    int[] check = {2, 3, 4, 2, 6};

    System.out.println(universe42(check));


}


 private static boolean universe42(int[]array){
        boolean check1 = false;
        boolean check2 = false;
        int two = 2;
        int four = 4;

        for(int i=0; i< array.length; i  ) {
            if (array[i] == two) {
                    check1 = true;
                System.out.println("check1");
            }
            else {
                System.out.println("check-------");
                break;
            }
            if (array[i]== four){
                check2=true;
            }


        }
        if(check1==true && check2== true){
            return true;
        }


        return false;
    }
    
}

CodePudding user response:

You're breaking the loop execution if array[i]==two is false, and it eventually always is, because at position 1 you have a 3, and you always run the first check.

You need to remove the break of the else.

CodePudding user response:

You need to break when you find a 4, not when you don't find a 2. Something like this:

boolean foundTwo = false;
for (int x : array) {
    if (x == 2) {
        foundTwo = true;
    } else if (x == 4) {
        break;
    }
}
return foundTwo;

If you want to make sure there's both a 2 and a 4, in the correct order, just return on 4 instead of breaking, and default to false otherwise:

boolean foundTwo = false;
for (int x : array) {
    if (x == 2) {
        foundTwo = true;
    } else if (x == 4) {
        return foundTwo;
    }
}
return false;
  • Related