Learn Java · lesson 37 of 61 · about 11 minutes
Project: Text Analyzer
Put up the sign outside the cinema: read a line, split it into words, title-case it and find the longest word, each with its own method.
What you'll learn
- Combine split, loops and StringBuilder
- Write small analysis methods
- Format a report
The sign outside
At the end of the night the manager types the line for the sign outside, like space PIRATES is back tonight. The desk tidies it into Space Pirates Is Back Tonight, counts the words, and finds the longest (the first one if there's a tie), so the manager knows whether it will fit. The line has spaces in it, so it's read with nextLine, but the line before it was read with in.next(), which leaves the rest of that line behind: one in.nextLine(); skips it first. An empty line means there's no sign tonight.
The plan
Each job is its own static method:
splitWords(text)splits into words, however many spaces are between themlongestWord(words)finds the longest wordtitleCase(words)capitalises each word with a StringBuilder
The analyzer
import java.util.Scanner;
public class Main {
static String[] words(String text) {
return text.trim().split("\\s+");
}
static String longest(String[] words) {
String best = "";
for (String w : words) if (w.length() > best.length()) best = w;
return best;
}
static int vowels(String text) {
int n = 0;
for (char c : text.toLowerCase().toCharArray()) if ("aeiou".indexOf(c) >= 0) n++;
return n;
}
static String titleCase(String[] words) {
StringBuilder sb = new StringBuilder();
for (String w : words) {
if (sb.length() > 0) sb.append(' ');
sb.append(Character.toUpperCase(w.charAt(0))).append(w.substring(1).toLowerCase());
}
return sb.toString();
}
public static void main(String[] args) {
String text = new Scanner(System.in).nextLine();
String[] w = words(text);
System.out.println("Words: " + w.length);
System.out.println("Longest: " + longest(w));
System.out.println("Vowels: " + vowels(text));
System.out.println("Title: " + titleCase(w));
}
}Output
Words: 5
Longest: phoebe
Vowels: 10
Title: Phoebe Learns Java Every DayTip
An empty line still splits into one word, the empty text, so check isBlank() before splitting a line that might have nothing on it.
Now try it yourself
This lesson is free in Codiqo, with 9 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.