Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Jul 2011
    Posts
    19
    Thanks
    12
    Thanked 0 Times in 0 Posts

    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?

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    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.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •