Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / October 2006

Tip: Looking for answers? Try searching our database.

How to jump out of several nested control structures?

Thread view: 
Shawn - 20 Oct 2006 18:44 GMT
Hi,

I am wondering how can I jump out of several layers of loops. break can
only jump out of the inner most loop.

for ( ...)  //layer 1
{
    for (...) //layer 2
    {
        for (...)  //layer 3
        {
           //code
           if (jump==true)  //How can I jump out of all the layers at once?       
           
        }
    }

}
Patricia Shanahan - 20 Oct 2006 18:52 GMT
> Hi,
>
> I am wondering how can I jump out of several layers of loops. break can
> only jump out of the inner most loop.

No, break can jump out of any labeled statement enclosing it.

See
http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html#6842

for the syntax and an example.

Patricia
Shawn - 20 Oct 2006 20:09 GMT
> No, break can jump out of any labeled statement enclosing it.
>
[quoted text clipped - 4 lines]
>
> Patricia

Wow. break is similar to GOTO, according to the following statements
from the link you gave to me:

"A break statement with label Identifier attempts to transfer control to
the enclosing labeled statement (§14.7) that has the same Identifier as
its label; this statement, which is called the break target, then
immediately completes normally. In this case, the break target need not
be a while, do, for, or switch statement. A break statement must refer
to a label within the immediately enclosing method or initializer block.
There are no non-local jumps."

I almost have never seen people using break as GOTO feature.
Patricia Shanahan - 20 Oct 2006 20:14 GMT
>> No, break can jump out of any labeled statement enclosing it.
>>
[quoted text clipped - 17 lines]
>
> I almost have never seen people using break as GOTO feature.

It is very different from GOTO, because it can ONLY be used to break out
of a statement enclosing the break.

That said, I'm obviously aware of it, but I don't think I've used it so
far in my own code.

Patricia
Shawn - 20 Oct 2006 20:23 GMT
> It is very different from GOTO, because it can ONLY be used to break out
> of a statement enclosing the break.

"Break out of a statement enclosing the break". What does it mean? I am
sorry.

According to the cited paragraph, it doesnt' need for loop, while loop,
etc. It seems the following code is legal:

public class MyClass
{
       ...//code

    public void myMethod()
    {
        ...//code
        if (wantToEnd) break here
        ...//more code

    here: System.out.println("I am going to exit");
          return;
    }

}

Do you think the above feature is GOTO?
Shawn - 20 Oct 2006 20:44 GMT
> It is very different from GOTO, because it can ONLY be used to break out
> of a statement enclosing the break.
[quoted text clipped - 3 lines]
>
> Patricia

Sorry. I see what you mean now.

here:
{
    ...//many layers inside
    if (jump==true) break here;  //jump out of here scope
    ...//more code executed if not jumped

}
//reach here by jump or by normal execution
Simon Brooke - 20 Oct 2006 22:35 GMT
>> No, break can jump out of any labeled statement enclosing it.
>>
>> See

http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html#6842

>> for the syntax and an example.
>
> Wow. break is similar to GOTO, according to the following statements
> from the link you gave to me:

Yup, that's why I prefer the 'special exception' solution. Jumping to
labels is spaghetti programming in the making, whereas a special exception
just unwinds the stack.

Signature

simon@jasmine.org.uk (Simon Brooke) http://www.jasmine.org.uk/~simon/

       my other car is #<Subr-Car: #5d480>
                               ;; This joke is not funny in emacs.

Robert Klemme - 20 Oct 2006 23:59 GMT
> Yup, that's why I prefer the 'special exception' solution. Jumping to
> labels is spaghetti programming in the making, whereas a special exception
> just unwinds the stack.

IMHO using exceptions for this is a case of abuse.  From my point of
view refactoring to another method and using "return" is much cleaner -
and probably faster, too.  Before I'd use an exception for a non
exceptional condition I'd rather use "break" with label.  However, so
far I never felt the need for any of those.  I typically use the
"return" solution or have proper loop conditions - whatever seems more
appropriate.

Regards

    robert
Mark Rafn - 21 Oct 2006 00:26 GMT
>Wow. break is similar to GOTO

Nope.  Break can only transfer control to an enclosing scope.  It can only
go to the end of a block.  GOTO can jump anywhere.  This is a humongous
difference.

That said, it can be abused.  I've seen code that contained
 do {
     stuff;
     if (!something) break;
     more stuff;
 } while (false);
 
As a way to avoid putting "more stuff" into a separate method because there
were a lot of local variables that would have to be passed in and out.

>There are no non-local jumps."

This is the key phrase that makes break safe and goto unsafe.
--
Mark Rafn    dagon@dagon.net    <http://www.dagon.net/>
Thomas Hawtin - 21 Oct 2006 12:39 GMT
> That said, it can be abused.  I've seen code that contained
>   do {
[quoted text clipped - 5 lines]
> As a way to avoid putting "more stuff" into a separate method because there
> were a lot of local variables that would have to be passed in and out.

Code like this can often be written more sensibly. But if the programmer
thought it not worth the costs of splitting into a separate method, the
technique doesn't seem completely unreasonable. (For the record I almost
did it once that I remember. I then just rearranged the code into a
clearer form.)

BTW, you don't need the do while false;:

    block: {
        stuff;
        if (!something) {
            break block; /***/
        }
        more stuff;
    }

FWIW: I think all break statements should have labels (although that is
unidiomatic) and continue should be outlawed (although I used it in an
interview the other week). Oh, and nested loops tend to be an indicator
that your method is getting a bit long (2D structures excepted).

Tom Hawtin
Tor Iver Wilhelmsen - 21 Oct 2006 09:47 GMT
> Wow. break is similar to GOTO,

GOTO is a *general* purpose jump. Most languages need *special*
purpose jumps - like Java's break, continue, while, if and for. The
difference is that GOTO's jump-anywhere nature makes it hard to
analyse flow compared to the restricted and block-oriented
alternatives.

The C# developers apparently chose to let the programmer shoot
themselves in the foot like that. But only within a method or switch
statement, of course.
Gordon Beaton - 20 Oct 2006 18:53 GMT
> I am wondering how can I jump out of several layers of loops. break
> can only jump out of the inner most loop.

No, it can jump much further than that. Label your loops and specify a
label in the break statement:

 gurka:
 for (...) {
   for (...) {
     break gurka;
   }
 }

/gordon

Signature

[ don't email me support questions or followups ]
g o r d o n  +  n e w s  @  b a l d e r 1 3 . s e

Simon Brooke - 20 Oct 2006 22:33 GMT
> I am wondering how can I jump out of several layers of loops. break can
> only jump out of the inner most loop.

Define your own exception class, wrap the whole lot in a try... catch, and
throw your special exception when you want to jump out of the loop.

Signature

simon@jasmine.org.uk (Simon Brooke) http://www.jasmine.org.uk/~simon/

               ;; Conservatives are not necessarily stupid,
               ;; but most stupid people are conservatives -- J S Mill

crazzybugger - 21 Oct 2006 00:30 GMT
> Hi,
>
[quoted text clipped - 14 lines]
>
> }

Just use the return statement with no arguements...........suppose you
have a loop say
for(...){
        for(...){
               for(,.....){
                                 //your code
                                 if(yourConditionSatisfied)
                                              return
                           }
                  }
       }
or you dont want the function to end
do something like this
try{
        for(...){
                   for(...){
                           for(...){
                                    //your code
                                    if(yourConditionSatisfied)
                                              throw new
yourException();
                                     }
                             }
                  }
}catch(YourException e){  //dummy }
  //continue your code here


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.