Spaces:
Running
Running
Create 16a. continue clause
Browse files
Week 1: Types, condition clauses and loops/16a. continue clause
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
it jumps back to the start line of the loop and the condition clause is evaluated again
|
| 2 |
+
when using the for loop, the CHANGE part is executed again BEFORE the evaluation of the CONDITION clause
|
| 3 |
+
|
| 4 |
+
VS
|
| 5 |
+
|
| 6 |
+
but when using the WHILE clause, continue can easily lead to a perpetual loop.
|
| 7 |
+
|
| 8 |
+
The following example attempts to print squares of even values.
|
| 9 |
+
However, the program remains in a perpetual loop: the continue statement aborts the loop, so the value of the number variable is not changed either.
|
| 10 |
+
|
| 11 |
+
public class Example {
|
| 12 |
+
public static void main(String[] args) {
|
| 13 |
+
// Program tries to calculate the squares of
|
| 14 |
+
// even elements
|
| 15 |
+
int num = 1;
|
| 16 |
+
while (num <= 30) {
|
| 17 |
+
// This causes an INFINITE LOOP, because
|
| 18 |
+
// variable num value never grows after
|
| 19 |
+
// the first odd value
|
| 20 |
+
if (luku % 2 == 1) {
|
| 21 |
+
continue;
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
int square = num * num;
|
| 25 |
+
System.out.println("The square of the number is: " + square);
|
| 26 |
+
num++;
|
| 27 |
+
}
|
| 28 |
+
}
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
|