SlideShare a Scribd company logo
1 of 3
Write a java program that compute the frequency of each word in the file
Task: Implementing Word Counter Problem description: Given a text file, you need to compute
the frequency of each word in the file. WordFrequency word: String count: int
+WordFrequency(String) +getWord): String +getCount): int +incCount): void TestClass +static
main(String[): void / /implements ArrayList of // WordFrequency The WordFrequency class
stores the frequency (count) of each word.
Solution
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
class FileIO {
public static void main (String[] args) throws IOException {
readTextFileInBinaryMode ("T.txt");
}
public static void readTextFileInBinaryMode (String fileName) {
FileReader fileReader = null;
LinkedHashMap <String, Integer> wordcount =
new LinkedHashMap <String, Integer> ();
try {
File file = new File (fileName);
fileReader = new FileReader (file);
int ch = -1;
boolean prevCharIsNotSpace = true;
StringBuilder strBuild = new StringBuilder ();
while ((ch = fileReader.read ()) != -1) {
if (ch == 32) {
if (prevCharIsNotSpace) {
Integer freq = wordcount.get (strBuild.toString ());
wordcount.put (strBuild.toString (), (freq == null ? : freq + 1));
}
prevCharIsNotSpace = false;
continue;
}
if (prevCharIsNotSpace == false)
strBuild = new StringBuilder ();
strBuild.append ((char) ch);
prevCharIsNotSpace = true;
}
}
catch (Exception e) {
System.out.println("Exception occurs"+e.getException());
}
//sorting
List <Map.Entry <String, Integer>> list =
new ArrayList <Map.Entry <String, Integer>> ();
for (Map.Entry <String, Integer> entry : wordcount.entrySet ()) {
System.out.println (entry.getKey () + " " + entry.getValue ());
list.add (entry);
}
Collections.sort (list, new MapComprator ());
for (Map.Entry <String, Integer> entry : list) {
System.out.println (entry.getKey () + " " + entry.getValue ());
}
}
}
class MapComprator implements Comparator <Map.Entry <String, Integer>> {
public int compare (Entry <String, Integer> o1, Entry <String, Integer> o2) {
return (o2.getValue ().compareTo (o1.getValue ()));
}
}

More Related Content

Similar to Write a java program that compute the frequency of each word in the fi.docx

Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
Alok Kumar
 
Object oriented programming la bmanual jntu
Object oriented programming la bmanual jntuObject oriented programming la bmanual jntu
Object oriented programming la bmanual jntu
Khurshid Asghar
 
Fundamentals of oop lecture 2
Fundamentals of oop lecture 2Fundamentals of oop lecture 2
Fundamentals of oop lecture 2
miiro30
 
Write a java program that allows the user to input the name of a file.docx
Write a java program that allows the user to input  the name of a file.docxWrite a java program that allows the user to input  the name of a file.docx
Write a java program that allows the user to input the name of a file.docx
noreendchesterton753
 
Please I am trying to get this code to output in -txt file- I need you.pdf
Please I am trying to get this code to output in -txt file- I need you.pdfPlease I am trying to get this code to output in -txt file- I need you.pdf
Please I am trying to get this code to output in -txt file- I need you.pdf
asenterprisestyagi
 
Java Program using RecursionWrite a program that reads in a file .pdf
Java Program using RecursionWrite a program that reads in a file .pdfJava Program using RecursionWrite a program that reads in a file .pdf
Java Program using RecursionWrite a program that reads in a file .pdf
duttakajal70
 
Java session08
Java session08Java session08
Java session08
Niit Care
 
Use Java to program the following.1. Create public java class name.pdf
Use Java to program the following.1. Create public java class name.pdfUse Java to program the following.1. Create public java class name.pdf
Use Java to program the following.1. Create public java class name.pdf
f3apparelsonline
 
I can not get my code to comply it gets mad that I have run declare mo.docx
I can not get my code to comply it gets mad that I have run declare mo.docxI can not get my code to comply it gets mad that I have run declare mo.docx
I can not get my code to comply it gets mad that I have run declare mo.docx
hamblymarta
 

Similar to Write a java program that compute the frequency of each word in the fi.docx (20)

JAVA Q2- Write a program that reads strings from the user and writes t.docx
JAVA Q2- Write a program that reads strings from the user and writes t.docxJAVA Q2- Write a program that reads strings from the user and writes t.docx
JAVA Q2- Write a program that reads strings from the user and writes t.docx
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
 
Object oriented programming la bmanual jntu
Object oriented programming la bmanual jntuObject oriented programming la bmanual jntu
Object oriented programming la bmanual jntu
 
Fundamentals of oop lecture 2
Fundamentals of oop lecture 2Fundamentals of oop lecture 2
Fundamentals of oop lecture 2
 
Write a java program that allows the user to input the name of a fil.docx
 Write a java program that allows the user to input  the name of a fil.docx Write a java program that allows the user to input  the name of a fil.docx
Write a java program that allows the user to input the name of a fil.docx
 
Write a java program that allows the user to input the name of a file.docx
Write a java program that allows the user to input  the name of a file.docxWrite a java program that allows the user to input  the name of a file.docx
Write a java program that allows the user to input the name of a file.docx
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Structure of java program diff c- cpp and java
Structure of java program  diff c- cpp and javaStructure of java program  diff c- cpp and java
Structure of java program diff c- cpp and java
 
Please I am trying to get this code to output in -txt file- I need you.pdf
Please I am trying to get this code to output in -txt file- I need you.pdfPlease I am trying to get this code to output in -txt file- I need you.pdf
Please I am trying to get this code to output in -txt file- I need you.pdf
 
Java Program using RecursionWrite a program that reads in a file .pdf
Java Program using RecursionWrite a program that reads in a file .pdfJava Program using RecursionWrite a program that reads in a file .pdf
Java Program using RecursionWrite a program that reads in a file .pdf
 
Java session08
Java session08Java session08
Java session08
 
Use Java to program the following.1. Create public java class name.pdf
Use Java to program the following.1. Create public java class name.pdfUse Java to program the following.1. Create public java class name.pdf
Use Java to program the following.1. Create public java class name.pdf
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPREC
 
Java Notes
Java Notes Java Notes
Java Notes
 
I can not get my code to comply it gets mad that I have run declare mo.docx
I can not get my code to comply it gets mad that I have run declare mo.docxI can not get my code to comply it gets mad that I have run declare mo.docx
I can not get my code to comply it gets mad that I have run declare mo.docx
 
For this assignment, you will develop starter code. After
For this assignment, you will develop starter code. After For this assignment, you will develop starter code. After
For this assignment, you will develop starter code. After
 
File Handling.pptx
File Handling.pptxFile Handling.pptx
File Handling.pptx
 
Write a program in Java that reads a set of doubles from a file, sto.pdf
Write a program in Java that reads a set of doubles from a file, sto.pdfWrite a program in Java that reads a set of doubles from a file, sto.pdf
Write a program in Java that reads a set of doubles from a file, sto.pdf
 
Con-FESS 2015 - Having Fun With Javassist
Con-FESS 2015 - Having Fun With JavassistCon-FESS 2015 - Having Fun With Javassist
Con-FESS 2015 - Having Fun With Javassist
 
Java quickref
Java quickrefJava quickref
Java quickref
 

More from noreendchesterton753

Spongy moths- Lymantria dispar- have four life cycle stages- egg- cate.docx
Spongy moths- Lymantria dispar- have four life cycle stages- egg- cate.docxSpongy moths- Lymantria dispar- have four life cycle stages- egg- cate.docx
Spongy moths- Lymantria dispar- have four life cycle stages- egg- cate.docx
noreendchesterton753
 

More from noreendchesterton753 (20)

Suppose the population of interest in a particular study is all Queen'.docx
Suppose the population of interest in a particular study is all Queen'.docxSuppose the population of interest in a particular study is all Queen'.docx
Suppose the population of interest in a particular study is all Queen'.docx
 
Suppose the Federal Reserve increases deposits at financial institutio.docx
Suppose the Federal Reserve increases deposits at financial institutio.docxSuppose the Federal Reserve increases deposits at financial institutio.docx
Suppose the Federal Reserve increases deposits at financial institutio.docx
 
Suppose that Edison and Hilary represent the only two consumers of blu.docx
Suppose that Edison and Hilary represent the only two consumers of blu.docxSuppose that Edison and Hilary represent the only two consumers of blu.docx
Suppose that Edison and Hilary represent the only two consumers of blu.docx
 
Suppose that 42- of Americans are obese- A) If 100 people are randomly.docx
Suppose that 42- of Americans are obese- A) If 100 people are randomly.docxSuppose that 42- of Americans are obese- A) If 100 people are randomly.docx
Suppose that 42- of Americans are obese- A) If 100 people are randomly.docx
 
Suppose I am teaching a class and the test comes and goes with two stu.docx
Suppose I am teaching a class and the test comes and goes with two stu.docxSuppose I am teaching a class and the test comes and goes with two stu.docx
Suppose I am teaching a class and the test comes and goes with two stu.docx
 
Suppose an economy is given by the following- Population -274 million.docx
Suppose an economy is given by the following- Population -274 million.docxSuppose an economy is given by the following- Population -274 million.docx
Suppose an economy is given by the following- Population -274 million.docx
 
Suppose a researcher conducted a study examining the effectiveness of.docx
Suppose a researcher conducted a study examining the effectiveness of.docxSuppose a researcher conducted a study examining the effectiveness of.docx
Suppose a researcher conducted a study examining the effectiveness of.docx
 
Supoese you have 'n' different individuals- and all of them to rearran.docx
Supoese you have 'n' different individuals- and all of them to rearran.docxSupoese you have 'n' different individuals- and all of them to rearran.docx
Supoese you have 'n' different individuals- and all of them to rearran.docx
 
Sunspot Beverages- Limited- of Fiji uses the weighted-average method i.docx
Sunspot Beverages- Limited- of Fiji uses the weighted-average method i.docxSunspot Beverages- Limited- of Fiji uses the weighted-average method i.docx
Sunspot Beverages- Limited- of Fiji uses the weighted-average method i.docx
 
Sunland Company has the following data-Compute total manufacturing cos.docx
Sunland Company has the following data-Compute total manufacturing cos.docxSunland Company has the following data-Compute total manufacturing cos.docx
Sunland Company has the following data-Compute total manufacturing cos.docx
 
Successful negotiating includes some kind of manipulation in order to.docx
Successful negotiating includes some kind of manipulation in order to.docxSuccessful negotiating includes some kind of manipulation in order to.docx
Successful negotiating includes some kind of manipulation in order to.docx
 
Subsidiary holds an allocated net operating loss (NOL) when it leaves.docx
Subsidiary holds an allocated net operating loss (NOL) when it leaves.docxSubsidiary holds an allocated net operating loss (NOL) when it leaves.docx
Subsidiary holds an allocated net operating loss (NOL) when it leaves.docx
 
Substances that dissolve readily in water are termed hydrophilic- They.docx
Substances that dissolve readily in water are termed hydrophilic- They.docxSubstances that dissolve readily in water are termed hydrophilic- They.docx
Substances that dissolve readily in water are termed hydrophilic- They.docx
 
subject FASHION The combination of which Roman terms most closely co.docx
subject FASHION   The combination of which Roman terms most closely co.docxsubject FASHION   The combination of which Roman terms most closely co.docx
subject FASHION The combination of which Roman terms most closely co.docx
 
Styling Conventions By only changing the case of some of the letters-.docx
Styling Conventions By only changing the case of some of the letters-.docxStyling Conventions By only changing the case of some of the letters-.docx
Styling Conventions By only changing the case of some of the letters-.docx
 
Students spend an average of $520 each semester on textbooks- Suppose.docx
Students spend an average of $520 each semester on textbooks- Suppose.docxStudents spend an average of $520 each semester on textbooks- Suppose.docx
Students spend an average of $520 each semester on textbooks- Suppose.docx
 
Species interactions determine an organism's fundamental niche- True F.docx
Species interactions determine an organism's fundamental niche- True F.docxSpecies interactions determine an organism's fundamental niche- True F.docx
Species interactions determine an organism's fundamental niche- True F.docx
 
Spongy moths- Lymantria dispar- have four life cycle stages- egg- cate.docx
Spongy moths- Lymantria dispar- have four life cycle stages- egg- cate.docxSpongy moths- Lymantria dispar- have four life cycle stages- egg- cate.docx
Spongy moths- Lymantria dispar- have four life cycle stages- egg- cate.docx
 
SPSS output of a binomial probability distribution with succes probabi.docx
SPSS output of a binomial probability distribution with succes probabi.docxSPSS output of a binomial probability distribution with succes probabi.docx
SPSS output of a binomial probability distribution with succes probabi.docx
 
Starting on the day Holly was born- her mother has invested $30 at the.docx
Starting on the day Holly was born- her mother has invested $30 at the.docxStarting on the day Holly was born- her mother has invested $30 at the.docx
Starting on the day Holly was born- her mother has invested $30 at the.docx
 

Recently uploaded

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 

Recently uploaded (20)

Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 

Write a java program that compute the frequency of each word in the fi.docx

  • 1. Write a java program that compute the frequency of each word in the file Task: Implementing Word Counter Problem description: Given a text file, you need to compute the frequency of each word in the file. WordFrequency word: String count: int +WordFrequency(String) +getWord): String +getCount): int +incCount): void TestClass +static main(String[): void / /implements ArrayList of // WordFrequency The WordFrequency class stores the frequency (count) of each word. Solution import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; class FileIO { public static void main (String[] args) throws IOException { readTextFileInBinaryMode ("T.txt"); } public static void readTextFileInBinaryMode (String fileName) { FileReader fileReader = null; LinkedHashMap <String, Integer> wordcount = new LinkedHashMap <String, Integer> ();
  • 2. try { File file = new File (fileName); fileReader = new FileReader (file); int ch = -1; boolean prevCharIsNotSpace = true; StringBuilder strBuild = new StringBuilder (); while ((ch = fileReader.read ()) != -1) { if (ch == 32) { if (prevCharIsNotSpace) { Integer freq = wordcount.get (strBuild.toString ()); wordcount.put (strBuild.toString (), (freq == null ? : freq + 1)); } prevCharIsNotSpace = false; continue; } if (prevCharIsNotSpace == false) strBuild = new StringBuilder (); strBuild.append ((char) ch); prevCharIsNotSpace = true; } } catch (Exception e) { System.out.println("Exception occurs"+e.getException()); } //sorting List <Map.Entry <String, Integer>> list = new ArrayList <Map.Entry <String, Integer>> (); for (Map.Entry <String, Integer> entry : wordcount.entrySet ()) { System.out.println (entry.getKey () + " " + entry.getValue ()); list.add (entry); } Collections.sort (list, new MapComprator ());
  • 3. for (Map.Entry <String, Integer> entry : list) { System.out.println (entry.getKey () + " " + entry.getValue ()); } } } class MapComprator implements Comparator <Map.Entry <String, Integer>> { public int compare (Entry <String, Integer> o1, Entry <String, Integer> o2) { return (o2.getValue ().compareTo (o1.getValue ())); } }