Problem Description Write a java program that counts the number of each vowels (
ID: 3759120 • Letter: P
Question
Problem Description
Write a java program that counts the number of each vowels (a, e, i, o and u), consonants and other characters in a text file and displays:
The number of a’s
The number of e’s
The number of i’s
The number of o’s
The number of u’s
The number of consonants
The number of other characters.
The vowel and consonant count is case insensitive.
Specifications
The program will need to do the following:
Ask for an input filename.
Display an error message if the file does not exist and ask them to reenter a filename.
Open the file.
Read each character.
Increment the appropriate counter.
Print out the results after the whole file has been read.
Ask the user if they would they would like to process another file.
If so, repeat steps 1 – 5.
If not, display a cheerful message goodbye and end the program.
Explanation / Answer
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Scanner;
public class File {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
while(true) {
System.out.print("Enter fileName: ");
String file = scan.next();
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(file),
Charset.forName("UTF-8")));
int c;
int a=0;
int e=0;
int i=0;
int o=0;
int u=0;
int conso = 0;
int other=0;
while((c = reader.read()) != -1) {
char character = (char) c;
character = Character.toLowerCase(character);
if (character == 'a')
a++;
else if (character == 'e')
e++;
else if (character == 'i')
i++;
else if (character == 'o')
o++;
else if (character == 'u')
u++;
else if (character >= 'a' && character <= 'z')
conso++;
else
other++;
}
System.out.println("Number of a's: "+a);
System.out.println("Number of e's: "+e);
System.out.println("Number of i's: "+i);
System.out.println("Number of o's: "+o);
System.out.println("Number of u's: "+u);
System.out.println("Number of consonants: "+conso);
System.out.println("Number of other characters: "+other);
System.out.print(" Enter 0 to quit or anyother to repeat: ");
int input = scan.nextInt();
if (input == 0) {
System.out.println("Goob bye");
break;
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.