// Reports statistics about a passage of text.

/// Returns the words of the text, stripped of punctuation and in lowercase.
ArrayList<String> wordList(String text) {
    ArrayList<String> words = new ArrayList<>();
    for (String raw : text.strip().split("\\s+")) {
        String lower = raw.toLowerCase();
        String cleaned = "";
        for (int i = 0; i < lower.length(); i++) {
            char c = lower.charAt(i);
            if (Character.isLetter(c) || c == '\'') {
                cleaned += c;
            }
        }
        if (!cleaned.isEmpty()) {
            words.add(cleaned);
        }
    }
    return words;
}

/// Returns the number of vowels in the text.
int countVowels(String text) {
    String lower = text.toLowerCase();
    int count = 0;
    for (int i = 0; i < lower.length(); i++) {
        if ("aeiou".indexOf(lower.charAt(i)) >= 0) {
            count++;
        }
    }
    return count;
}

/// Returns the longest word in a list, or an empty string if there are none.
String longestWord(ArrayList<String> words) {
    String longest = "";
    for (String word : words) {
        if (word.length() > longest.length()) {
            longest = word;
        }
    }
    return longest;
}

/// Returns the mean length of the words, or 0.0 for an empty list.
double averageWordLength(ArrayList<String> words) {
    if (words.isEmpty()) {
        return 0.0;
    }
    int total = 0;
    for (String word : words) {
        total += word.length();
    }
    return (double) total / words.size();
}

/// Prints a report of statistics about the text.
void analyze(String text) {
    ArrayList<String> words = wordList(text);
    int sentences = 0;
    for (int i = 0; i < text.length(); i++) {
        if (".!?".indexOf(text.charAt(i)) >= 0) {
            sentences++;
        }
    }
    int noSpaces = text.replace(" ", "").length();
    double average = averageWordLength(words);

    IO.println("=".repeat(34));
    IO.println(String.format("%-23s%11d", "Characters:", text.length()));
    IO.println(String.format("%-23s%11d", "Characters (no spaces):", noSpaces));
    IO.println(String.format("%-23s%11d", "Words:", words.size()));
    IO.println(String.format("%-23s%11d", "Sentences:", sentences));
    IO.println(String.format("%-23s%11d", "Vowels:", countVowels(text)));
    IO.println(String.format("%-23s%11s", "Longest word:", longestWord(words)));
    IO.println(String.format("%-23s%11.1f", "Average word length:", average));
    IO.println("=".repeat(34));
}

void main() {
    String sample = "The quick brown fox jumps over the lazy dog. "
            + "Programming is the art of telling another human what one wants "
            + "the computer to do. Is that not remarkable?";

    analyze(sample);
}

// From Groundwork, chapter 8 (ch08-strings-as-data), box 27.
// This example is from Groundwork, licensed CC BY-NC-SA 4.0.
// Run with: java ch08_27.java
