JAVA program Your assignment, working alone or with a partner is to do the follo
ID: 3821694 • Letter: J
Question
JAVA program
Your assignment, working alone or with a partner is to do the following:
Then using a map, count the number of occurrences of each word and determine how many of each of them there are.
DataFile1.txt
love
gentlenss
love
peace
love
kindness
love
peace
understanding
kindness
joy
peace
understanding
friendship
gentlenss
goodness
love
peace
goodness
love
gentlenss
control
understanding
understanding
gentlenss
love
peace
patience
control
kindness
gentlenss
love
peace
joy
goodness
peace
friendship
Explanation / Answer
/*
* The java program WordOccurence that
* read a text file called DataFile1.txt
* and then print the count of occurences
* of each string to console.
* */
//WordOccurence.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class WordOccurence
{
public static void main(String[] args)
{
//create an instance of HashMap with string and Integer
//key and value
Map<String, Integer> frequency = new HashMap<String, Integer>();
Scanner filereader=null;
try
{
filereader = new Scanner(new File("DataFile1.txt"));
//read until end of file
while (filereader.hasNextLine())
{
String word = filereader.nextLine();
Integer count = frequency.get(word);
//check if count is not null
if (count != null)
{
//increment the count by 1 in word
frequency.put(word, count + 1);
}
else
{
//otherwise set count 1
frequency.put(word, 1);
}
}
//print heading
System.out.printf("----------------------------- ");
System.out.printf("%-15s %-15s ","Word","Frequency");
System.out.printf("----------------------------- ");
//print word and its frequency in the file
for(String word:frequency.keySet())
{
System.out.printf("%-15s %5d ",word,frequency.get(word));
}
//close filereader
filereader.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Exist");
}
}
}//end of class
-------------------------------------------------------------------------------------------------------------------
DataFile1.txt
love
gentlenss
love
peace
love
kindness
love
peace
understanding
kindness
joy
peace
understanding
friendship
gentlenss
goodness
love
peace
goodness
love
gentlenss
control
understanding
understanding
gentlenss
love
peace
patience
control
kindness
gentlenss
love
peace
joy
goodness
peace
friendship
-------------------------------------------------------------------------------------------------------------------
Sample output:
-----------------------------
Word Frequency
-----------------------------
love 8
gentlenss 5
friendship 2
joy 2
peace 7
patience 1
understanding4
control 2
kindness 3
goodness 3
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.