Java continues at the end of if

I have a sample code from a book, and the author always uses the continuation at the end of the if.

Example:

int a = 5; if(a == 5) { // some code continue; } 

Now it makes no sense to me. Could there be any relation to quality management behind this, or am I just missing some big point?

+8
java if-statement continue
source share
4 answers

Perhaps this piece of code was inside a loop ( for/while/do...while )? otherwise, it makes no sense to put continue inside the conditional statement.

In fact, a lost continue (for example, one that is not nested somewhere inside the loop statement) will result in a continue cannot be used outside of a loop error at compile time.

+17
source share

Continue is used to advance to the next iteration of the loop. So something like this will make sense. Now you can use all the conditions (your a==5 for a break) and any business logic that you wanted (mine is a stupid, far-fetched example).

 StringBuilder sb = new StringBuilder(); for(String str : strings) { sb.append(str); if(str.length() == 0) continue; // next loop if empty str = str.substring(1); sb.append(str); if(str.length() == 0) continue; // next loop if empty str = str.substring(1); sb.append(str); if(str.length() == 0) continue; // next loop if empty sb.append(str); } 
+5
source share

It is sometimes useful to force a loop iteration. That is, you can continue the loop, but stop processing the rest of the code in your body for this particular iteration. This, in fact, goto just past the body of the cycle, until the end of the cycle. The continue statement performs this action. In while and do-while loops, the continue statement causes control to be passed directly to the conditional expression that controls the loop. In a for loop, control first passes to the iteration part of the for statement, and then to the conditional expression. For all three cycles, any intermediate code bypasses. Here is an example program that uses a continuation to output two numbers for each line: // The demonstration continues.

 class Continue { public static void main(String args[]) { for(int i=0; i<10; i++) { System.out.print(i + " "); if (i%2 == 0) continue; System.out.println(""); } } } 

This code uses the% operator to parity i. If so, the loop continues without printing a new line. Here is the result of this program:

0 1
2 3
4 5
6 7
8 9

+2
source share

Typically, a continuation is used to exit deeply nested loops or simply for clarity (debatable).

Sometimes continue is also used as a placeholder to create an empty body body clearer element .

 for (count = 0; foo.moreData(); count++) continue; 

This is a matter of taste, which I personally do not use.

0
source share

All Articles