Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats wrong with this while loop? [duplicate]

boolean r = false ; int s = 0 ;
while (r == false) ; 
{
    s = getInt() ; 
    if (!(s>=0 && s<=2)) System.out.println ("try again not a valid response") ; 
    else r = true ; 
}

The text never displays itself even when a 3 or a 123 is entered and the loop never terminates. Whats wrong here?

like image 355
David Avatar asked Apr 09 '10 20:04

David


3 Answers

You have a semicolon after the condition. When you use braces to specify a block for your while you don't use a semicolon.

like image 125
Daniel DiPaolo Avatar answered Sep 23 '22 00:09

Daniel DiPaolo


Remove the ';' after while.

like image 21
Alex Avatar answered Sep 21 '22 00:09

Alex


Others have pointed out the bug, but your code is scary in other ways that will eventually trip you up:

if (!(s>=0 && s<=2)) System.out.println ("try again not a valid response") ; 
else r = true ; 

That's bad because you can easily intend more than one statement to run in the case of the if or else clause. Use curly braces and avoid placing conditional statements on a single line:

if (!(s>=0 && s<=2))
{
    System.out.println ("try again not a valid response");
}
else
{
    r = true;
}

It's easier to read and far less likely to introduce hard-to-see bugs.

like image 26
Jonathon Faust Avatar answered Sep 23 '22 00:09

Jonathon Faust