Home > Mobile >  Can inner and outer loops interrupt and resume one after another?
Can inner and outer loops interrupt and resume one after another?

Time:04-14

I have an existing loop that draws the labels and textboxes in two horizontal lines (Line 1 as Label, Line 2 as textboxes). At that time, the loop was based on the definite requirement that there will not be more than 12 elements of each type. This was written using two loops (one loop representing a label, another as a text box):

Draw labels

for (int i = 2, i<hdrlabel.length; i  ){
coldef.add(new ColDefType("",hdrLabel[i],"varchar",false,15,"HDR" String.valueOf(i),1,i==2?"%-25s":"",6,"LABEL",true,""));
}

Draw Text Boxes

LinkedHashmap<String,String> row = dbVal.get(i)    
for (int j = 1, i<hdrlabel.length-1; i  ){
        coldef.add(new ColDefType(j==1?row.get(hdrLabel[j]:"",row.get(hdrLabel[j 1],"decimal5",false,15,row.get(hdrLabel[0]) String.valueOf(j),i 2),j==1?"%-25s":"",6,"TXTFLD",true,""));
    }

Now, as to take account of number of days, the number of elements (in hdrLabel.length-2) is now increased to a max of 31 for each component type. Due to spacing issues for mobile and tablet viewing, it was determined that it's best if we draw up to 12 elements per line. What I am looking for is that if the number of elements of each type is more than 12, it should be drawn like:

  • Line 1: Labels 1-12
  • Line 2: Text Box 1-12
  • Line 3: Labels 13-24
  • Line 4: Text Box 13-24
  • Line 5: Labels 25-31
  • Line 6: Text Box 25-31

If the number of elements is between 15 to 24, boxes and labels in lines 5 and 6 are not required to be drawn.

Is there any way to use only two loops where we pause one loop when either reaches the 12 / 24 element, run the other loop and then resume the former loop?

I could not find a much more leaner way to do this, as the closest I could get is to break it to several for loops, but it's definitely not efficient if given of the dynamic number of max elements:

  • Line 1 - (for i=2, i<14, i ) - break at 13
  • Line 2 - (for j=1, j<13,j ) - break at 12
  • Line 3 - (for i=14, i<26, i ) - break at 26
  • Line 4 - (for j=13, i<25, i ) - break at 25
  • Line 5 - (for i=26, i<hdrLabel.length, i ) - break at 31
  • Line 6 - (for j=25, i<hdrLabel.length-1, i ) - break at 31

CodePudding user response:

Not sure if this is what you want since it used 3 loops, but at least it works (assuming you want loop 1 to always happen first)

int i_start = 2;
int j_start = 1;
int i_terminate = 32;
int j_terminate = 32;
int next_i, next_j;
while (true) {
    next_i = Math.min(i_start   12, i_terminate);
    next_j = Math.min(j_start   12, j_terminate);
    for (int i = i_start; i < next_i;   i) {
        // do something
    }
    
    for (int j = j_start; j < next_j;   j) {
        // do something
    }

    i_start = next_i;
    j_start = next_j;

    if (i_start == i_terminate && j_start == j_terminate) {
        break;
    }
}
  • Related