BeginnerLesson 4 of 16
Loops – Java
for, for-each, while and do-while.
The classic for loop has an initializer, a condition and a step. The for-each loop iterates over arrays and collections.
for (int i = 0; i < 3; i++) {
System.out.println("Round " + i);
}
String[] fruechte = {"Apple", "Pear", "Cherry"};
for (String frucht : fruechte) {
System.out.println(frucht.toUpperCase());
}while checks the condition before each pass, do-while only afterwards (so it runs at least once). break ends the loop, continue jumps to the next round.
int n = 0;
while (true) {
n++;
if (n % 2 == 0) continue;
if (n > 7) break;
System.out.println(n); // 1 3 5 7
}
int versuch = 0;
do {
versuch++;
System.out.println("Attempt " + versuch);
} while (versuch < 2);For number sequences there is also IntStream, which works like a range in other languages:
import java.util.stream.IntStream;
IntStream.rangeClosed(1, 5).forEach(i -> System.out.print(i + " ")); // 1 2 3 4 5
System.out.println();
System.out.println(IntStream.range(0, 5).sum()); // 10WarningDo not change the loop variable inside the loop body, and in a for loop watch out for
< versus <= – the classic off-by-one error.