user3131148
user3131148

Reputation: 353

Don't understand why Conditional "OR" operator not working for me?

Am doing this online exercise and one question is:

We'll say that a number is "teen" if it is in the range 13..19 inclusive. Given 2 int values, return true if one or the other is teen, but not both

So I should return true if one of the int values that it passes into my method is in the range of 13 and 19 but return false if both are in the range; This is the code I wrote:

 public boolean loneTeen(int a, int b) {
  if ( a >= 13 && a <= 19 || b >= 13 && b <= 19 )
  return true;
  else
  return false;
}

basically if integer a is between 13 and 19 inclusive or if integer b is between 13 and 19 inclusive I return true otherwise I return false. When I test this it works except If I pass in 13 and 13 for integer a and b, I get true instead of false. My question is I've looked up the conditional "OR(||)" operator and it says that:

So when I use "Or" operator like my code above doesn't it mean if a is in the range return true or if b is in the range return true but if both are in the range return false? what is the differance between using

Upvotes: 3

Views: 2962

Answers (3)

Djaildo Quaresma
Djaildo Quaresma

Reputation: 29

The || (or) operator returns true if at least one of the parts is true. Now if both parts are true, is at least one of the parts true? The answer is yes. That's why when the first part is evaluated as true, it's unnecessary to check the other part.

What you're looking for is the exclusive or (^). This operator will return true if only one of the parts is true. So, to get the results you want, all you need to do is to replace || for ^, like so:

    public boolean loneTeen(int a, int b) {
        if ( (a >= 13 && a <= 19) ^ (b >= 13 && b <= 19) )
            return true;
        else
            return false;
    }

Edit: Parentheses inside the if statement added after the discussion with David Wallace.

Upvotes: 0

user3639170
user3639170

Reputation: 11

The problem is the lack of braces.

Ideally you would write something like this:

public boolean isPersonTeen(int a) {
  if ( a >= 13 && a <= 19)
      return true;
  // If you came here means the condition failed.
  return false;
}

Now you can just check XOR

 isPersonTeen(a) ^ isPersonTeen(b)

Hth!

Upvotes: 1

arshajii
arshajii

Reputation: 129572

Basically all you want is for exactly one of the values isTeen(a) and isTeen(b) to be true, so use XOR:

if ((a >= 13 && a <= 19) ^ (b >= 13 && b <= 19))
  • If you replace ^ with ||, you allow for the possibility of both a and b being teen numbers.

  • If you replace ^ with &&, you are essentially saying that you always want both a and b to be teen numbers.

Neither of these are what you want. XOR, on the other hand, works for your problem perfectly.

Upvotes: 9

Related Questions