MY mENU


Thursday, 9 February 2012

continue statement in java


The Continue Statement skips the current iteration of a for, while, or do-while loop.

Unlabeled : The Unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop.

Example :

class ContinueDemo {
public static void main(String[] args) {

String searchMe = "peter piper picked a peck of pickled peppers";
int max = searchMe.length();
int numPs = 0;

for (int i = 0; i < max; i++) {
//interested only in p's
if (searchMe.charAt(i) != 'p')
continue;

//process p's
numPs++;
}
System.out.println("Found " + numPs + " p's in the string.");
}
}


Here is the output of this program:

Found 9 p's in the string.

- The above program, ContinueDemo , steps through a String, counting the occurences of the letter "p". If the current character is not a p, the Continue Statement skips the rest of the loop and proceeds to the next character. If it is a "p", the program increments the letter counts.


To see this effect more clearly, try removing the Continue Statement and recompiling. When you run the program again, the count will be wrong, saying that it found 35 p's instead of 9.

Labeled
 : A Labeled Continue Statement skips the current iteration of an outer loop marked with the given label.

Example :

class ContinueWithLabelDemo {
public static void main(String[] args) {

String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;

int max = searchMe.length() - substring.length();

test:
for (int i = 0; i <= max; i++) {
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++)
!= substring.charAt(k++)) {
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" :
"Didn't find it");
}
}


Here is the output from this program.

Found it

- The above example program, ContinueWithLabelDemo, uses nested loops to search for a substring within another string. Two nested loops are required: one to iterate over the substring and one to iterate over the string being searched. The following program, ContinueWithLabelDemo, uses the labeled form of Continue to skip an iteration in the outer loop.

No comments:

Post a Comment