wayoo
wayoo

Reputation: 125

check if array contains certain int BEFORE another int

I need to check if an array contains a 1 and then later in the array contains a 2.

What I have coded only checks if both are in there, not if one is before the other. How could I do this?

if(array[i] == 1)
    count++;
  else if(array[i] == 2)
    count++;
  }

  if(count > 1)
    System.out.print("true");
    else
     System.out.print("false");

Comparing the index of the values works!

    if (nums[i] == 1)
      value1 = i;
      else if(nums[i] == 2)
        value2 = i;
  }

   if (value2 > value1)
     System.out.print("true");
   else
    System.out.print("false");

Upvotes: 1

Views: 69

Answers (1)

Luke
Luke

Reputation: 1724

This oughta do it!

public void hasOneThenTwo(int[] a) {
    bool hasOne = false;
    for (int i = 0; i < a.length; ++i) {
        if (!hasOne && a[i] == 1) {
            hasOne = true;
        } else if (hasOne && a[i] == 2) {
            return true;
        }
    }
    return false;
}

Upvotes: 1

Related Questions