Forums Register Login

outer inner program

+Pie Number of slices to send: Send
package com.vaannila.student;

public class MyFor{
public static void main(String argv[]){
int i;
int j;
outer:
for (i=1;i <3;i++)
inner:
for(j=1; j<3; j++) {
if (j==2)
continue outer;
System.out.println("Value for i=" + i + " Value for j=" +j);
}
}
}


I was trying above example from link
http://www.jchq.net/certkey/0202certkey.htm
got output like


Value for i=1 Value for j=1
Value for i=2 Value for j=1




I was trying to understand the output. Any links, ideas, resources,sample code highly appreciated. thanks in advance.
+Pie Number of slices to send: Send
 

you earlier wrote:. . . resources . . .

Pencil and paper.
+Pie Number of slices to send: Send
Hi Mathew,

Putting code examples within code tags makes the display a lot nicer and easier to read.



The output you got is correct, what you need to understand is the meaning of the key word continue and how that works with a labelled loop.

So whenever the variable j for the loop labelled inner equals 2 the statement continue outer; gets called which means all statements below this till the ending curly brace of the loop labelled outer are skipped over and a new iteration of the loop labeled outer begins by first checking if the loop should run or not.

In the above example we could replace continue outer; with break inner;. Though it does not mean these keywords do the same thing. The only reason break inner; is because there are no lines of code after the ending curly brace for the loop labelled inner. The keyword break does exactly that breaks out of the innermost loop or the loop which you’ve labelled the break to happen on. If there were lines of code after the curly brace of the loop labelled inner than those would execute. But if we used the keyword continue and there were lines of code after the curly brace of the loop labelled inner than those lines will NOT be executed.

Anyway researching labelled loops and the keywords of continue and break, you’ll probably find better explanations.

Hope it all helps though.
+Pie Number of slices to send: Send
 

Callum Ludwig wrote: . . . Anyway researching labelled loops and the keywords of continue and break, you’ll probably find better explanations. . . .

. . . and explanations why that is poor coding style.

Thank you for the good explanation, Callum Ludwig
You know it is dark times when the trees riot. I think this tiny ad is their leader:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 850 times.
Similar Threads
Help with Continue ..
Label question
labelled nested for loop
Marcus Green Mock #1 Q 21
Some doubt about Continue
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 00:50:53.