Note: Submission of this project with a passing score is a requisite for continu
ID: 668211 • Letter: N
Question
Note: Submission of this project with a passing score is a requisite for continuing with the course.
There is no grace period for this project. Please submit by the deadline.
You are a programming intern at the linguistics department and your boss has come to ask for
your help with a simple task. She would like you to write a simple program that analyzes some text and
outputs the frequency of its letters.
You will write a program, Project1.java, which repeatedly asks the user for input until the user
enters “DONE” and then outputs a chart showing the relative frequencies of the letters a-z and the letter
with the highest frequency. Capital letters A-Z are treated as if they were lower case letters. Any other
characters are ignored. Frequencies are rounded to the nearest integer (e.g.: 3.333 % becomes 3 % and
3.666 % becomes 4 %). The chart and output of your program should be exactly as shown in the sample runs below:
Enter text at the prompt to calculate letter frequencies. Enter DONE when finished with text input.
Enter a line of text: Frequency analysis is cool.
Enter a line of text: If you use it on long text you can discover some interesting things.
Enter a line of text: Try it out!
Enter a line of text: DONE
A total of 86 letters of the alphabet were processed.
a b c d e f g h i j k l m n o p q r s t u v w x y z %
* * * * * * * * * * * * * * * * * * * 1
. . .
* * * 10
The most common letter is i with a frequency of 10 %.
Explanation / Answer
import java.lang.reflect.Array;
import java.util.Scanner;
public class Project1 {
public static void main(String str[])
{
//DECLARE ARRAY
int[] arr=new int[26];
int freq=0; //DECLARE FREQ VARIABLE
for(int i=0;i<26;i++) //INITIALIZE ARRAY TO 0
arr[i]=0;
int count=0; //DECLARE AND DEFINE COUNT TO 0
String s1=new String("");
String s2=new String("");
Scanner input;
input = new Scanner ( System.in ); //SCANNER VARIABLE
System.out.println("Enter text at the prompt to calculate letter frequencies. Enter DONE when finished with text input.");
do //DO WHILE LOOP
{
System.out.print("Enter a line of text:");
s1=input.nextLine();
s2=s2.concat(s1);
}while(!(s1.equals("DONE")));
s2=s2.substring(0, s2.length()-4);
s2=s2.toLowerCase();
for(int i=0;i<s2.length();i++)
{
if(s2.charAt(i)>=97 && s2.charAt(i)<=122)
{
count++;
arr[s2.charAt(i)-97]++;
}
}
System.out.println("A total of "+ count+ " letters of the alphabet were processed.");
for(int i=0;i<26;i++)
{
arr[i]=Math.round(100*arr[i]/count);
}
freq=arr[0];
for(int i=1;i<26;i++)
{
if(freq<arr[i])
freq=arr[i];
}
System.out.println("a b c d e f g h i j k l m n o p q r s t u v w x y z");
System.out.println("The most common letter is with a frequency of "+ freq+"%");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.