Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

Need help with a simple problem.

Mack Grill
Greenhorn
Posts: 29

I am trying to answer this question:

"Write the correct logic expression (that could be used as a Java conditional expression) that evaluates to true if the number x is between 1 and 100 (both exclusive) or the number is negative."

if ((x >=1 && x <= 100) || x < 0) { }

But I am being told this is wrong for this reason:

"this range was supposed be exclusive"

Stuart A. Burkett
Ranch Hand
Posts: 679
'exclusive' means the specified limits are not considered valid values

Mack Grill
Greenhorn
Posts: 29

Great but how am should I keep them separate when I need to use || ?

Stuart A. Burkett
Ranch Hand
Posts: 679
Mack Grill wrote:
Great but how am should I keep them separate when I need to use || ?

I don't understand what you're asking.
The problem is in this part

The specification says
Mack Grill wrote:the number x is between 1 and 100 (both exclusive)

but your code allows 1 and 100 as valid values.

Akhilesh Trivedi
Ranch Hand
Posts: 1608
a <= 10
means "a can have all the values below AND 10" i.e. "10 is also included"

a <10
means "a can have all the values below 10" i.e. "10 is not included"

Mack Grill
Greenhorn
Posts: 29

sorry i meant to say how should i use the || in the code and how do I involve a negative number?

"f the number x is between 1 and 100 (both exclusive) OR the number is negative"

Stuart A. Burkett
Ranch Hand
Posts: 679
Mack Grill wrote:
sorry i meant to say how should i use the || in the code and how do I involve a negative number?

"f the number x is between 1 and 100 (both exclusive) OR the number is negative"

You've already done that. That part of the expression is fine.

fred rosenberger
lowercase baba
Bartender
Posts: 12234
36
another way of saying "between 1 and 100 (both exclusive)" is "the number is greater than 1 and less than 100".

In other words, 1 should return false, and 100 should return false.

The whole request could be re-written as

The number is greater than 1 and less than 100....OR the number is negative.

Winston Gutkowski
Bartender
Posts: 10527
64
Mack Grill wrote:I have this answer:
if ((x >=1 && x <= 100) || x < 0) { }

I hope I'm not muddying the waters here, but when you think about compound conditions, it's a good idea to try and eliminate the most likely quickest.
All other things being equal (which they often aren't)
x < 0
is true for a lot more values than
(x >=1 && x <= 100)
and its also quicker to check, so
if (x < 0 || (x >=1 && x <= 100))
is likely to run faster than what you had. I actually find it easier to read too.

Winston