Challenge: Vowel Counter
Completed
Read one line of text and print how many vowels (a e i o u, upper or lower case) it contains.
Input
One line of text.
Output
The number of vowels.
Example
Input
Data Structures In Java
Output
8
Editor
Java
Hints
Lower-case each character first so 'A' and 'a' are the same.
"aeiou".indexOf(c) >= 0 is a quick way to ask “is c a vowel?”.
Solution explanation
One pass over the text: O(n).
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
int vowels = 0;
for (int i = 0; i < line.length(); i++) {
char c = Character.toLowerCase(line.charAt(i));
if ("aeiou".indexOf(c) >= 0) vowels++;
}
System.out.println(vowels);
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module