IV. Grading 1. A program that does not run will receive 0 point. 2. There is a 10-20 points deduction for each major error, e.g., missing a word in the output. 3. There is a 1-9 points deduction for each minor error, e.g., incorrect format of output. 4. A program that does not follow the guidelines will lose 1-10 points. 5. Any type of cheating is not tolerated. You may be asked to explain your program in person. V. Bonus features (optional) You may implement as many bonus features as you want. If you implement any bonus feature in your program, please put a comment in your Blackboard submission and in your main Java file. In your comments, explain which bonus feature(s) you implemented. 1. (2 points) Your program will ignore the case of words, e.g., it will count “On” and “on” as the same word; 2. (8 points) Your program will also print the total occurrences of the words. For example, Display entries in ascending order of key a: 2 an: 2 eye: 2 fish: 1 fit: 1 hook: 2 into: 2 like: 1 me: 1 open: 1 you: 1 Total: 16
Please find the program attached below. Here we have used a TreeMap because it orders the keys in the ascending order. Comments have been provided at each line for better understanding. Have a look at the program.
import java.util.*;
public class CountOccurences {
public static void main(String[] args) {
//enclose your input within quotes.
String sentence = "Hi, this is a test sentence. THIS IS A TEST";
showFrequency(sentence); //call the showFrequency method
}
public static void showFrequency(String sentence)
{
//tree map is created because it orders keys in ascending order
TreeMap<String, Integer> map = new TreeMap<>();
//remove all punctuation marks and split sentence on basis of whitespace
String[] words = sentence.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+");
//iterate through the array of words in the sentence
for(String s : words)
{
if(map.containsKey(s)) //if word is already present in the set
{
int oc = map.get(s); //get it's count
map.put(s, ++oc); //increment the count and put it back to the set
}
else
{
//if word was not already present, it is found first time.
map.put(s, 1); //put it with 1 frequency
}
}
//total number of words in the sentence is equal to the length of the words array
int total = words.length;
//iterate through the TreeSet using for each loop
//entry set consists of both key and value
for (Map.Entry<String,Integer> entry : map.entrySet())
{
String word = entry.getKey(); //get word
int freq = entry.getValue(); //get it's frequency
System.out.print(word+": "+freq+" "); //print word and corresponding frequency
}
System.out.println("Total: "+total); //print total number of words in the sentence.
}
}
Output:
Refer to below screenshot for an idea of indentation:
Please reach out for any other clarifications or doubts in the comments section. If you find this helpful, Please give an upvote. Thanks :)
Get Answers For Free
Most questions answered within 1 hours.