Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 07-09-2012, 04:11 PM   PM User | #1
laylo
New Coder

 
Join Date: Jul 2011
Posts: 19
Thanks: 12
Thanked 0 Times in 0 Posts
laylo is an unknown quantity at this point
Unhappy Java Beginner Question-break statement

for(int i=5; i>=2; i--)
{
switch(i)
{
case 1: case 3:
System.out.println("YES"); break;
case 2: case 4: case 5: System.out.println("NO");

}
}
System.out.println("OK");
}



ok so i know this outputs :-
Code:
NO NO YES NO OK
but in this book im reading, when it come's to the value 3, where case 3 is executed doesn't the break statement break outside this loop? than proceeding to the next value 2. Im kind of confused, why does it continue with the loop when at case 3 it has the break statement, shouldn't go out and continue with whatever code is below?
laylo is offline   Reply With Quote
Old 07-09-2012, 05:09 PM   PM User | #2
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,653
Thanks: 4
Thanked 2,451 Times in 2,420 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
No, the break statement is for the switch, not the loop. The break has to appear at the loop level to break the loop.
I highly recommend not using break and avoiding continue as much as you can in regards to looping. IMO it creates a new layer of complication when attempting to debug the code. I'd recommend instead using a simple conditional for said case.
PHP Code:
boolean bContinue true;
for (
int i 0100 && bContinue; ++i)
{
    if (
>= 50)
    {
        
bContinue false;
    }

For example.
Fou-Lu is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 06:56 AM.


Advertisement
Log in to turn off these ads.