Alternative way to a == b, without boolean

216 views Asked by At

I made simple program. I want to stop it when the user enters "5".

Relevant code:

do { 
   System.out.println("Enter 5 to quit");    
   a = scanner.nextInt();     
   b = a==5;     
} while (b = true);

Of course earlier I named variables (int a, boolean b etc.)

Why doesn't it work when I type:

}while (b ==5)

PS. Is there a way to refactor code (while change to for)?

5

There are 5 answers

0
java_student On BEST ANSWER

while (b = true);

you are using = here (assignment) in place of == (relational)

then you used this : b = a==5; now as per operator precedence, first a==5 will be executed which may return true or false.

this wont work : while (b ==5) as it is not identical to while (b ==true) in Java, In C/C++, true is any nonzero value and false is zero. In Java, true and false are nonnumeric values that do not relate to zero or nonzero.

so, you can try :

while (b == true);

or

while (a!=5);

0
hpopiolkiewicz On
do { 
   System.out.println("Enter 5 to quit");     
} while (scanner.nextInt() != 5);
0
Scary Wombat On

When doing

}while (b = true);

you are assigning the value of true to b so it will always be true

What you want is either

}while (b != true);

or

}while (!b);
0
Paul Arockiam On

While you need to read the basics of java well, let me answer your question of why

} while (b == 5);

won't work. It is because you are trying to compare a boolean (you said you had declared b as boolean) with 5 (which is an integer).

0
Eran On

If entering 5 should get you out of the loop, your condition should be :

do {
    ...
} while (!b); // or while (b == false)

while (b == true) and while (a == 5) will keep you in the loop only if 5 was entered.