used the frequencies with which the 26 letters of the English alphabet appear in
ID: 3774660 • Letter: U
Question
used the frequencies with which the 26 letters of the English alphabet appear in normal prose. Write a Java program which will tally letter frequencies in any plain text file a user wants. Find and use an appropriate Collections data structure to store letters and the number of occurrences.
Your program should prompt the user to enter a filename, open the file, scan the text character-by-character, and count the occurrences of each of the 26 letters. You should not distinguish between upper and lower case letters, and punctuation should be ignored.
Your program should print out each letter and its relative frequency amongst the letters in the file. That is, if there are 300 letters (excluding puncuation and whitespace) in the file, and 24 of them are the letter “w”, then w’s relative frequency is 0.08. Of course, we will test your program on the original Conan Doyle story!
Explanation / Answer
Code:
Words.java
package frequency;
public class Words
{
String word;
int count;
double frequency;
public Words()
{
word="";
count=0;
frequency=0.0;
}
public Words(String w)
{
word=w;
count=0;
frequency=0.0;
}
}
Frequency.java
package frequency;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Frequency {
static Scanner sc=new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException {
Words w[]=new Words[20];
int count=0;
System.out.println("Enter the file name");
String name=sc.nextLine();
File f=new File(name);
// Read the file
Scanner input = new Scanner(f);
int flag1=0;
while(input.hasNext()) {
//Each word converted to lower case
String word = input.next().toLowerCase();
//if first word
if (count==0)
{
w[count]=new Words(word);
count++;
}
else
{
flag1=0;
for(int i=0;i<count;i++)
{
// If word alraedy there
if(word.equals(w[i].word))
{
w[i].count++;
flag1=0;
break;
}
else
{
flag1=1;
}
}
if(flag1==1)
{
w[count]=new Words(word);
count++;
}
}
}
for(int k=0;k<count;k++)
{
System.out.println(w[k].word);
System.out.print(((float)w[k].count)/((float)count));
System.out.println();
}
}
}
Output:
run:
Enter the file name
input.txt
this
0.14285715
reference
0.14285715
has
0.14285715
been
0.14285715
prepared
0.14285715
for
0.0
users
0.0
BUILD SUCCESSFUL (total time: 6 seconds)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.