Create a Java Program that will read a file and count the number of words beginn
ID: 3673627 • Letter: C
Question
Create a Java Program that will read a file and count the number of words beginning with each letter of the alphabet. You should ignore upper and lower case letter differences and report all words that begin with either an upper or lower case letter. If you encounter a non-letter first character, please ignore this word. For example, ignore 3ABC, 500 or similar words.
Sample output:
Please enter the file name you wish to read
TestFile.txt
A has 4 words.
B has 0 words,
C has 0 words.
D has 0 words.
Explanation / Answer
import java.util.*;
import java.lang.*;
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
class Assignment9
{
public static void main ( String [] args )
{
int [] lettercount = new int [26];
int temp;
try (BufferedReader br = new BufferedReader(new FileReader("testing.txt")))
{
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
str = sCurrentLine.toLowerCase();
String[] splited = str.split(" ");
for ( int k = 0;k< splited.length; k++ ){
if (Character.isLetter(splited[k].charAt(0))){
lettercount[splited[k].charAt(0) - 'a']++;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
for(int k =0 ;k<26;k++){
temp = 65+k;
System.out.println( (char) (temp) + " = " + lettercount[k]);}
}
}