1

Please have a look at the following code (Java)

 while((str=br.readLine())!=null)
        {
            int tempCounter=0;

            for(int i=0;i<str.length();i=i+3)
            {
                String word = str.substring(i, i+3);
                //  System.out.println(word);
                int insert = db.insert(index, word);
                if(insert<0)
                {
                    break;
                }
                tempCounter++;
            }
            index++;

            System.out.println("Index Updated: "+index);
            System.out.println(String.valueOf("Total words in this run: "+tempCounter));

            if(index==5)
            {
                break;
            }

        }

if insert is less than 0, the I need to break both for and while loops. How can I do this?

Problem here is I need to break "both" loops if insert is less than 0. And you can't add 2 break commands one after another, even with labels.

PeakGen
  • 21,894
  • 86
  • 261
  • 463
  • 1
    use [labledstatements](http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.7) – Santhosh Apr 25 '14 at 12:34
  • or you can do if(index==5 || insert<0) { break; } – Hunsu Apr 25 '14 at 12:37
  • 1
    @AntonH I disagree that this is a duplicate of the linked question. Certainly one possible answer to this is "use a label", but this question isn't asking about labels directly. – JonK Apr 25 '14 at 13:04

6 Answers6

1

You may try this simple example to see how a labeled loop works:

public static void main(String[] args) {
    int i = 0; int j = 0;
    EXIT: for (; i < 10; i++) {
        for (; j < 10; j++) {
            if (i * j > 50) {
                break EXIT;
            }
        }
        j = 0;
    }
    System.out.printf("Finished with i=%s and j=%s\n", i, j);

}

OUTPUT:

Finished with i=6 and j=9
JonK
  • 2,097
  • 2
  • 25
  • 36
Harmlezz
  • 7,972
  • 27
  • 35
  • 1
    Just because you *can* write `for` loops and `if` statements without braces, doesn't mean you *should*... – JonK Apr 25 '14 at 12:59
  • In my opinion, if a single body statement appears on the same line you do not have to add braces (assuming you do not use auto-formating of your IDE, which I never do). But this is another topic, with many different opinion on it. Defensive programmer would always use braces, but for improved readability, I sometimes omit them (rarely). – Harmlezz Apr 25 '14 at 13:02
  • I wouldn't consider a `for` loop an `if` statement and a `break` on the same line more readable. However, as you stated this is a matter of opinion and personal preference, so I'll drop the matter. – JonK Apr 25 '14 at 13:07
0

+1.. @AntonH.. label is an first option.. if you are confused how to use label.. you can use a boolean variable like below..

while (...) {

    boolean brk = false;
    for (...) {
        if(insert<0)
        {   brk = true;
            break;
        }
    }
    if(brk)
    {
        break;
    }
}
niiraj874u
  • 2,180
  • 1
  • 12
  • 19
0
 while((str=br.readLine())!=null)
 {
        int tempCounter=0;
        boolean check = false;
        for(int i=0;i<str.length();i=i+3)
        {
            String word = str.substring(i, i+3);
            //  System.out.println(word);
            int insert = db.insert(index, word);
            if(insert<0)
            {
                check = true;
                break;
            }
            tempCounter++;
        }
        index++;
        if(check)
            break;

        System.out.println("Index Updated: "+index);
        System.out.println(String.valueOf("Total words in this run: "+tempCounter));

        if(index==5)
        {
            break;
        }

    }

You can do by this way

xxlali
  • 996
  • 2
  • 15
  • 43
0

Your question is already partly answered here. Use the label in front of the line of the while loop, e.g. OUTMOST, then when the insert is less than 0, 'break OUTMOST'. For example:

OUTMOST:
    while(someCondition) {
        for(int i = 0; i < someInteger; i++) {
            if (someOtherCondition)
                break OUTMOST;
        }
    }
Community
  • 1
  • 1
0

One approach is to use an exception, depending on the expected result of the db.insert routine.

In short, create a new EDBInsertionException exception (a class extending Exception) and raise the exception in your for loop.

try
{

    while((str=br.readLine())!=null)
    {
        int tempCounter=0;

        for(int i=0;i<str.length();i=i+3)
        {
            String word = str.substring(i, i+3);
            //  System.out.println(word);
            int insert = db.insert(index, word);
            if(insert<0)
            {
                throw new EDBInsertionException("No record inserted: " + insert);
            }
            tempCounter++;
        }
        index++;

        System.out.println("Index Updated: "+index);
        System.out.println(String.valueOf("Total words in this run: "+tempCounter));

        if(index==5)
        {
            break;
        }

    }
}
catch (EDBInsertionException e)
{
    // MZ: The database insertion has failed
    log.error(e.getMessage(), e);

    // MZ: Supplemental action: Delegate, escalate, rollback, etc           
}

EDIT

Expanded the example to illustrate a potential usage of an (user) exception.

Marius
  • 3,043
  • 1
  • 15
  • 24
  • This isn't what Exceptions are for. – JonK Apr 25 '14 at 12:57
  • Please elaborate, i believe this to be an exception to the default workflow (No record could be inserted, thus introducing an exception to the expected result). – Marius Apr 25 '14 at 13:06
  • Using an exception as a flow control mechanism (which this *is* doing) is bad practice. Without greater context to this, `-1` could well just be indicating `I'm done inserting stuff now, carry on`, which is certainly *not* an exceptional condition. – JonK Apr 25 '14 at 13:21
  • Of course thats dependent of the expected behaviour of the db.insert command. Depending on that, this will or will not be an anti pattern. In general, i would expect an insert statement to raise an exception if it is unable to, but if the code leaves it to the caller an exception would be in order. – Marius Apr 25 '14 at 13:33
0

IMO, an exception is inappropriate; a label is rare and not likely to be understood by future readers.

Invoking KISS principle, why not just use an extra flag and augment the expression used in each loop:

boolean isInsertFail = false;

while((! isInsertFail) && (str=br.readLine())!=null))
        {
            int tempCounter=0;

            for(int i=0;(! isInsertFail) && i<str.length();i=i+3)
            {
                String word = str.substring(i, i+3);
                //  System.out.println(word);
                int insert = db.insert(index, word);
                if(insert<0)
                {
                    isInsertFail = true;
                }
                tempCounter++;
            }

            if (!isInsertFail) {
                index++;

                System.out.println("Index Updated: "+index);
                System.out.println(String.valueOf("Total words in this run: "+tempCounter));

                if(index==5)
                {
                    break;
                }
            }
        }

Note that in Eclipse, one could click on isInsertFail, and the syntax highlighting should illustrate its use.

Michael Easter
  • 23,733
  • 7
  • 76
  • 107
  • anyway, monitoring the upper loop with `label` and breaking only that will break the sub loop too right? – PeakGen Apr 25 '14 at 14:09