4. Count with a loop

Replace App.kalm to practice counting words before adding file I/O:

App.kalm
space stats

pub fun main() -> Unit:
    fix text = "a   quiet morning"
    var words = 0
    for word in text.split("\\s+"):
        if not word.isBlank():
            words += 1

    sayLine(@"$words words")
App.kalm
space stats

pub fun main() -> Unit {
    fix text = "a   quiet morning"
    var words = 0
    for word in text.split("\\s+") {
        if not word.isBlank() {
            words += 1
        }
    }
    sayLine(@"$words words")
}
App.java
package stats;

public final class App {
    public static void main(String[] args) {
        final String text = "a quiet morning";
        int words = 0;
        for (final String word : text.split("\\s+"))
            if (!word.isBlank()) words += 1;
        System.out.println(words + " words");
    }
}

Java's split accepts a regular expression. \\s+ matches consecutive whitespace; the doubled slash is the string escape. The blank check makes empty input count as zero words. for traverses the array with an immutable loop binding.

Terminal
kalm.bat run
Terminal
kalm.bat run
Terminal
kalm run
Terminal
kalm run
Terminal
kalm run
Terminal
kalm run
Terminal
kalm run
Terminal
kalm run
Text
3 words

Try empty text, leading spaces, and tabs. They should not add words.

Functions and flow covers branches and loop control.

Save the complete program below as App.kalms in a folder of your choice. Each lesson replaces this file; the shell does not load neighboring project files.

App.kalm
pub fun main() -> Unit:
    fix text = "a   quiet morning"
    var words = 0
    for word in text.split("\\s+"):
        if not word.isBlank():
            words += 1

    sayLine(@"$words words")
App.kalm
pub fun main() -> Unit {
    fix text = "a   quiet morning"
    var words = 0
    for word in text.split("\\s+") {
        if not word.isBlank() {
            words += 1
        }
    }
    sayLine(@"$words words")
}
App.kalms
fix text = "a   quiet morning"
var words = 0
for word in text.split("\\s+"):
    if not word.isBlank():
        words += 1

sayLine(@"$words words")
App.kalms
fix text = "a   quiet morning"
var words = 0
for word in text.split("\\s+") {
    if not word.isBlank() {
        words += 1
    }
}
sayLine(@"$words words")
App.java
void main() {
    final String text = "a quiet morning";
    int words = 0;
    for (final String word : text.split("\\s+"))
        if (!word.isBlank()) words += 1;
    System.out.println(words + " words");
}
Terminal
kalm.bat shell -f App.kalms
Terminal
kalm.bat shell -f App.kalms
Terminal
kalm shell -f App.kalms
Terminal
kalm shell -f App.kalms
Terminal
kalm shell -f App.kalms
Terminal
kalm shell -f App.kalms
Terminal
kalm shell -f App.kalms
Terminal
kalm shell -f App.kalms
Text
3 words