Codiqo

Learn Java · lesson 20 of 61 · about 8 minutes

break and continue

Let the queue in one character at a time: skip the gaps with continue, stop when the doors close with break, and walk a String with charAt or for-each.

What you'll learn

  • Exit with break
  • Skip with continue
  • Walk every character of a String

The queue at the door

The usher types the queue outside as a line like AC.A!AA: an A is an adult, a C a child, a . a gap where someone left, and ! the moment the doors close. The desk walks the line in order, skips the gaps, lets everyone else in, and stops at the !: nobody behind it gets in.

Changing a loop's flow

break leaves the loop; continue skips to the next lap. Searching usually ends with break as soon as the answer is found.

Skip, stop and search

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

        int found = -1;
        for (int n = 20; n <= 30; n++) {
            if (n % 7 == 0) {
                found = n;
                break;
            }
        }
        System.out.println("First multiple of 7: " + found);
    }
}

Output

1 3 5 7
First multiple of 7: 21

Walking a String

for (int i = 0; i < text.length(); i++) visits every position, and text.charAt(i) gives the character there. Java's for-each loop, for (char c : text.toCharArray()), does the same without an index. It needs an array, so for (char c : text) on its own doesn't compile.

Counting vowels with for-each

public class Main {
    public static void main(String[] args) {
        String word = "education";
        int vowels = 0;
        for (char c : word.toCharArray()) {
            if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') vowels++;
        }
        System.out.println(vowels + " vowels");
    }
}

Output

5 vowels

Letting the queue in

public class Main {
    public static void main(String[] args) {
        String queue = "AC.A!AA";
        int letIn = 0;
        int children = 0;
        for (int i = 0; i < queue.length(); i++) {
            char c = queue.charAt(i);
            if (c == '!') {
                System.out.println("Doors closed.");
                break;
            }
            if (c == '.') {
                continue;
            }
            letIn++;
            if (c == 'C') {
                children++;
            }
        }
        System.out.println("Let in: " + letIn + ", children: " + children);
    }
}

Output

Doors closed.
Let in: 3, children: 1

Now try it yourself

This lesson is free in Codiqo, with 11 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.