SlideShare a Scribd company logo
1 of 2
Download to read offline
Write a program CountWords in Java that reads text from a file and breaks it up into individual
words. Insert the words into a tree set. At the end of the input file, print all words, followed by
the size of the resulting set. This program determines how many unique words a text file has. If
the file is not found, give the user a chance to select another file.
Solution
Code:
package chegg;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.TreeSet;
import javax.swing.text.html.HTMLDocument.Iterator;
public class Test {
public static void main(String args[]) throws IOException
{
BufferedReader br = null;
String sCurrentLine;
TreeSet ts = new TreeSet();
br = new BufferedReader(new FileReader("C:/Users/ansharm5/Desktop/chegg"));
while ((sCurrentLine = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(sCurrentLine);
while(st.hasMoreTokens())
{
ts.add(st.nextToken());
}
}
System.out.println("Total no. of words: "+ ts.size());
java.util.Iterator iterator = ts.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next() + " ");
}
}
}

More Related Content

Similar to Write a program CountWords in Java that reads text from a file and b.pdf

Basics of java 2
Basics of java 2Basics of java 2
Basics of java 2
Raghu nath
 
I need help with this Java assignment. Please include comments throu.pdf
I need help with this Java assignment. Please include comments throu.pdfI need help with this Java assignment. Please include comments throu.pdf
I need help with this Java assignment. Please include comments throu.pdf
sales98
 
Change the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdfChange the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdf
secunderbadtirumalgi
 
PAGE 1Input output for a file tutorialStreams and File IOI.docx
PAGE  1Input output for a file tutorialStreams and File IOI.docxPAGE  1Input output for a file tutorialStreams and File IOI.docx
PAGE 1Input output for a file tutorialStreams and File IOI.docx
alfred4lewis58146
 
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
 

Similar to Write a program CountWords in Java that reads text from a file and b.pdf (20)

Basics of java 2
Basics of java 2Basics of java 2
Basics of java 2
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for Mainframers
 
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
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
File Handling.pptx
File Handling.pptxFile Handling.pptx
File Handling.pptx
 
In JavaWrite a program that reads a text file that contains a gra.pdf
In JavaWrite a program that reads a text file that contains a gra.pdfIn JavaWrite a program that reads a text file that contains a gra.pdf
In JavaWrite a program that reads a text file that contains a gra.pdf
 
I need help with this Java assignment. Please include comments throu.pdf
I need help with this Java assignment. Please include comments throu.pdfI need help with this Java assignment. Please include comments throu.pdf
I need help with this Java assignment. Please include comments throu.pdf
 
Change the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdfChange the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdf
 
Basic input-output-v.1.1
Basic input-output-v.1.1Basic input-output-v.1.1
Basic input-output-v.1.1
 
Java file
Java fileJava file
Java file
 
PAGE 1Input output for a file tutorialStreams and File IOI.docx
PAGE  1Input output for a file tutorialStreams and File IOI.docxPAGE  1Input output for a file tutorialStreams and File IOI.docx
PAGE 1Input output for a file tutorialStreams and File IOI.docx
 
OOP Language Powerpoint
OOP Language PowerpointOOP Language Powerpoint
OOP Language Powerpoint
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz
 
Java 7 & 8 New Features
Java 7 & 8 New FeaturesJava 7 & 8 New Features
Java 7 & 8 New Features
 
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
 
15. text files
15. text files15. text files
15. text files
 
ExtraFileIO.pptx
ExtraFileIO.pptxExtraFileIO.pptx
ExtraFileIO.pptx
 
Introduction
IntroductionIntroduction
Introduction
 
In Java Write a program that reads a file that contains only on.pdf
In Java Write a program that reads a file that contains only on.pdfIn Java Write a program that reads a file that contains only on.pdf
In Java Write a program that reads a file that contains only on.pdf
 
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
 

More from rushabhshah600

art F You decide to cross the reciprocal translocation strain to a pu.pdf
art F You decide to cross the reciprocal translocation strain to a pu.pdfart F You decide to cross the reciprocal translocation strain to a pu.pdf
art F You decide to cross the reciprocal translocation strain to a pu.pdf
rushabhshah600
 
Ecosystem ecologyWhy are rain forests wet and deserts dry Compare.pdf
Ecosystem ecologyWhy are rain forests wet and deserts dry Compare.pdfEcosystem ecologyWhy are rain forests wet and deserts dry Compare.pdf
Ecosystem ecologyWhy are rain forests wet and deserts dry Compare.pdf
rushabhshah600
 
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
rushabhshah600
 
Distinguish between cell fate and cell commitment. How can one assay.pdf
Distinguish between cell fate and cell commitment. How can one assay.pdfDistinguish between cell fate and cell commitment. How can one assay.pdf
Distinguish between cell fate and cell commitment. How can one assay.pdf
rushabhshah600
 
Differentiate the processes of oogenesis and spermatogenesis. Are th.pdf
Differentiate the processes of oogenesis and spermatogenesis. Are th.pdfDifferentiate the processes of oogenesis and spermatogenesis. Are th.pdf
Differentiate the processes of oogenesis and spermatogenesis. Are th.pdf
rushabhshah600
 
City GUIWrite a Java GUI program which reads data about US cities..pdf
City GUIWrite a Java GUI program which reads data about US cities..pdfCity GUIWrite a Java GUI program which reads data about US cities..pdf
City GUIWrite a Java GUI program which reads data about US cities..pdf
rushabhshah600
 
Briefly describe the contributions to the quality movement made by e.pdf
Briefly describe the contributions to the quality movement made by e.pdfBriefly describe the contributions to the quality movement made by e.pdf
Briefly describe the contributions to the quality movement made by e.pdf
rushabhshah600
 
Background Angiosperms (flowering plants) are the largest Phylum in .pdf
Background  Angiosperms (flowering plants) are the largest Phylum in .pdfBackground  Angiosperms (flowering plants) are the largest Phylum in .pdf
Background Angiosperms (flowering plants) are the largest Phylum in .pdf
rushabhshah600
 

More from rushabhshah600 (20)

Give an expression for the pattern inventory of 2-colorings of the ed.pdf
Give an expression for the pattern inventory of 2-colorings of the ed.pdfGive an expression for the pattern inventory of 2-colorings of the ed.pdf
Give an expression for the pattern inventory of 2-colorings of the ed.pdf
 
For the 4 arguments below, proceed as followsBREAK DOWN THE ARGU.pdf
For the 4 arguments below, proceed as followsBREAK DOWN THE ARGU.pdfFor the 4 arguments below, proceed as followsBREAK DOWN THE ARGU.pdf
For the 4 arguments below, proceed as followsBREAK DOWN THE ARGU.pdf
 
External respiration includes all of these processes EXCEPT _____. r.pdf
External respiration includes all of these processes EXCEPT _____.  r.pdfExternal respiration includes all of these processes EXCEPT _____.  r.pdf
External respiration includes all of these processes EXCEPT _____. r.pdf
 
art F You decide to cross the reciprocal translocation strain to a pu.pdf
art F You decide to cross the reciprocal translocation strain to a pu.pdfart F You decide to cross the reciprocal translocation strain to a pu.pdf
art F You decide to cross the reciprocal translocation strain to a pu.pdf
 
Ecosystem ecologyWhy are rain forests wet and deserts dry Compare.pdf
Ecosystem ecologyWhy are rain forests wet and deserts dry Compare.pdfEcosystem ecologyWhy are rain forests wet and deserts dry Compare.pdf
Ecosystem ecologyWhy are rain forests wet and deserts dry Compare.pdf
 
b) Analyze your network IP packets headers and contents.Solu.pdf
b) Analyze your network IP packets headers and contents.Solu.pdfb) Analyze your network IP packets headers and contents.Solu.pdf
b) Analyze your network IP packets headers and contents.Solu.pdf
 
A type A man is the son of a type O father and type A mother. If he .pdf
A type A man is the son of a type O father and type A mother. If he .pdfA type A man is the son of a type O father and type A mother. If he .pdf
A type A man is the son of a type O father and type A mother. If he .pdf
 
A One-Way Analysis of Variance is a way to test the equality of thre.pdf
A One-Way Analysis of Variance is a way to test the equality of thre.pdfA One-Way Analysis of Variance is a way to test the equality of thre.pdf
A One-Way Analysis of Variance is a way to test the equality of thre.pdf
 
5 000-0 SolutionEquity multiplier = Total Assets Equityor, .pdf
5 000-0 SolutionEquity multiplier = Total Assets  Equityor, .pdf5 000-0 SolutionEquity multiplier = Total Assets  Equityor, .pdf
5 000-0 SolutionEquity multiplier = Total Assets Equityor, .pdf
 
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
 
4 (4 points). How would you describe the difference in cell structur.pdf
4 (4 points). How would you describe the difference in cell structur.pdf4 (4 points). How would you describe the difference in cell structur.pdf
4 (4 points). How would you describe the difference in cell structur.pdf
 
Distinguish between cell fate and cell commitment. How can one assay.pdf
Distinguish between cell fate and cell commitment. How can one assay.pdfDistinguish between cell fate and cell commitment. How can one assay.pdf
Distinguish between cell fate and cell commitment. How can one assay.pdf
 
Differentiate the processes of oogenesis and spermatogenesis. Are th.pdf
Differentiate the processes of oogenesis and spermatogenesis. Are th.pdfDifferentiate the processes of oogenesis and spermatogenesis. Are th.pdf
Differentiate the processes of oogenesis and spermatogenesis. Are th.pdf
 
Define induction and give an example of deductive reasoningSolu.pdf
Define induction and give an example of deductive reasoningSolu.pdfDefine induction and give an example of deductive reasoningSolu.pdf
Define induction and give an example of deductive reasoningSolu.pdf
 
A report says that the between-subjects factor of participants sal.pdf
A report says that the between-subjects factor of participants sal.pdfA report says that the between-subjects factor of participants sal.pdf
A report says that the between-subjects factor of participants sal.pdf
 
City GUIWrite a Java GUI program which reads data about US cities..pdf
City GUIWrite a Java GUI program which reads data about US cities..pdfCity GUIWrite a Java GUI program which reads data about US cities..pdf
City GUIWrite a Java GUI program which reads data about US cities..pdf
 
What is the role of sulfur chemoautotrophs in the sulfur cycle Deco.pdf
What is the role of sulfur chemoautotrophs in the sulfur cycle  Deco.pdfWhat is the role of sulfur chemoautotrophs in the sulfur cycle  Deco.pdf
What is the role of sulfur chemoautotrophs in the sulfur cycle Deco.pdf
 
What is the PDU at Layer 4 calledA. DataB. SegmentC. Packet.pdf
What is the PDU at Layer 4 calledA. DataB. SegmentC. Packet.pdfWhat is the PDU at Layer 4 calledA. DataB. SegmentC. Packet.pdf
What is the PDU at Layer 4 calledA. DataB. SegmentC. Packet.pdf
 
Briefly describe the contributions to the quality movement made by e.pdf
Briefly describe the contributions to the quality movement made by e.pdfBriefly describe the contributions to the quality movement made by e.pdf
Briefly describe the contributions to the quality movement made by e.pdf
 
Background Angiosperms (flowering plants) are the largest Phylum in .pdf
Background  Angiosperms (flowering plants) are the largest Phylum in .pdfBackground  Angiosperms (flowering plants) are the largest Phylum in .pdf
Background Angiosperms (flowering plants) are the largest Phylum in .pdf
 

Recently uploaded

SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code Examples
Peter Brusilovsky
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
中 央社
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 

Recently uploaded (20)

24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge App
 
SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code Examples
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio App
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptx
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptx
 
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMDEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
 
Trauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical PrinciplesTrauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical Principles
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptx
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
Including Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdfIncluding Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdf
 
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxAnalyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
 

Write a program CountWords in Java that reads text from a file and b.pdf

  • 1. Write a program CountWords in Java that reads text from a file and breaks it up into individual words. Insert the words into a tree set. At the end of the input file, print all words, followed by the size of the resulting set. This program determines how many unique words a text file has. If the file is not found, give the user a chance to select another file. Solution Code: package chegg; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.StringTokenizer; import java.util.TreeSet; import javax.swing.text.html.HTMLDocument.Iterator; public class Test { public static void main(String args[]) throws IOException { BufferedReader br = null; String sCurrentLine; TreeSet ts = new TreeSet(); br = new BufferedReader(new FileReader("C:/Users/ansharm5/Desktop/chegg")); while ((sCurrentLine = br.readLine()) != null) { StringTokenizer st = new StringTokenizer(sCurrentLine); while(st.hasMoreTokens()) { ts.add(st.nextToken()); } } System.out.println("Total no. of words: "+ ts.size()); java.util.Iterator iterator = ts.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next() + " ");