GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes continue label Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "continue label" Watch "continue label" New topic
Author

continue label

pradeepta chopra
Ranch Hand

Joined: Jul 05, 2008
Posts: 137
class A{
public static void main(String[] args){
int age=10;
label:
while(age<=18)
{
if(age==16)
{

System.out.println("16");
continue label;
}

System.out.println("nottt");
age++;
}
}
}


output:
n infinite loop printing 16??
why is it so shouldnt it print
nott
nott
nott
nott
nott
16
nott
nott
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39095
    
  23
You ought to Use Code Tags to preserve the indentation, then print it out and follow the flow of execution with a pencil. Then the problem will become obvious.

There are good reasons why the JavaRanch style guide disapproves of labelled continue. Read them. It is regarded as equivalent to "goto" and many people (myself included) look on it as poor programming style.
pradeepta chopra
Ranch Hand

Joined: Jul 05, 2008
Posts: 137
i will keep the above point in mind while posting next time.
thank you
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39095
    
  23
You're welcome.
Larry Frissell
Ranch Hand

Joined: May 16, 2008
Posts: 82
    
    2
Did you find the problem? (Hint- what happens to age after printing "16")
pradeepta chopra
Ranch Hand

Joined: Jul 05, 2008
Posts: 137
well i guess that it prints nott for 5 times and when it becomes 16 the condition (age==16)becomes true and it prints 16 then due to continue statement it moves back to the label
so age++ never executes after age become 16
so age==16 always evaluates to true after the first encounter and thus the infinite looping
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39095
    
  23
Correct
pradeepta chopra
Ranch Hand

Joined: Jul 05, 2008
Posts: 137
yipppee
 
Consider Paul's rocket mass heater.
 
subject: continue label