Write a program that reads a file a character at a time and prints out how many
ID: 3760003 • Letter: W
Question
Write a program that reads a file a character at a time and prints out how many times the vowels a e i o u occur (in upper- or lowercase).
Complete the following file:
Vowels.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Vowels
{
public static void main(String[] args) throws FileNotFoundException
{
String vowels = "aeiou";
int[] counters = new int[vowels.length()];
Scanner console = new Scanner(System.in);
System.out.print("Input file: ");
String inputFileName = console.next();
. . .
for (int i = 0; i < vowels.length(); i++)
{
System.out.println(vowels.charAt(i) + ": " + counters[i]);
}
}
}
Explanation / Answer
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;
public class Vowels
{
public static void main(String[] args) throws IOException
{
String vowels = "aeiou";
int[] counters = new int[vowels.length()];
Scanner console = new Scanner(System.in);
System.out.print("Input file: ");
String inputFileName = console.next();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(new FileInputStream(new File(inputFileName))));
int c = 0;
while((c = buffer.read()) != -1) {
char character = Character.toLowerCase((char) c);
switch (character) {
case 'a':
counters[0]++;
break;
case 'e':
counters[1]++;
break;
case 'i':
counters[2]++;
break;
case 'o':
counters[3]++;
break;
case 'u':
counters[4]++;
break;
default:
break;
}
}
for (int i = 0; i < vowels.length(); i++)
{
System.out.println(vowels.charAt(i) + ": " + counters[i]);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.