• Post Reply Bookmark Topic Watch Topic
  • New Topic

outer inner program  RSS feed

 
Mathew Lee
Ranch Hand
Posts: 238
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Marshal
Posts: 55761
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you earlier wrote:. . . resources . . .
Pencil and paper.
 
Callum Ludwig
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Marshal
Posts: 55761
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!