Stupid (yet simple) error

G

gajo

I have this code:

int i = -5;
while ((i<0) & (i>=100))
i = Integer.parseInt(stdin.readLine());
// stdin is a BufferedReader

It's supposed to repeatedly read the users input until the user types a
number between 0 and 100. However, whenever I start the program it accepts
that i=-5 and an error occurs because of this.
Why?

Gajo
 
B

Bjorn Abelli

...
int i = -5;
while ((i<0) & (i>=100))
i = Integer.parseInt(stdin.readLine());
// stdin is a BufferedReader

It's supposed to repeatedly read the users input until
the user types a number between 0 and 100.

The condition you have written can *never* evaluate to true. (i can never be
*both* less than zero *and* greater or equal to 100).

I guess you're looking for:

while ((i < 0) || (i >= 100))

Bjorn A
 
C

Chris Smith

gajo said:
I have this code:

int i = -5;
while ((i<0) & (i>=100))
i = Integer.parseInt(stdin.readLine());
// stdin is a BufferedReader

It's supposed to repeatedly read the users input until the user types a
number between 0 and 100. However, whenever I start the program it accepts
that i=-5 and an error occurs because of this.
Why?

I don't know what you mean by "an error occurs", but it's clearly not
possible to satisfy the condition "((i < 0) & (i >= 100))", so the input
will never actually happen. Perhaps you meant "|" (and it's better to
use the short-cutting operators unless you have a specific reason not
to, so I'd use "||" instead.)

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top