Abhishek Sharma - 5 months ago 16

Java Question

Given 2 integers and condition

`negative`

- return if one is below zero and one is above zero and
`true`

is`negative`

.`false`

- return if both are below zero and
`true`

is`negative`

.`true`

- return otherwise.
`false`

Tests:

`posNeg(1, -1, false) expected: true`

posNeg(-1, 1, false) expected: true

posNeg(-4, -5, true) expected: true

posNeg(-4, 5, true) expected: false

My solution to the problem is :

`public boolean posNeg(int a, int b, boolean negative) {`

return ((((a>0) && (b<0)) || ((a<0) && (b>0))) || (((a<0) && (b<0)) &&(negative)));

}

But It is wrong for the case

`posNeg(-4, 5, true) expected: false | actual: true`

I think my solution is right after checking again several times.

Kindly let me know where I am wrong. Why this solution is incorrect?

Answer

You have three cases in an or relation to each other. Since one of the cases is "a is negative and b is positive", it will return true.

You need to make sure the first two cases only return true if negative is false.

For example instead of

```
((a>0) && (b<0))
```

write

```
(a > 0 && b < 0 && !negative)
```