Question: Java Write a program that reads all words from a file and, using a Stream, prints how many of them are the word the. This

Java

Write a program that reads all words from a file and, using a Stream, prints how many of them are the word the.

This is my current code:

import java.io.File; import java.io.IOException; import java.util.Scanner; import java.util.*;

/** * * Write a program that reads all words from a file and, using a Stream, * * prints all distinct words with at most four letters. * * from Horstmann, Big Java 6th Ed. */

public class PrintDistinctWords {

public static void main(String[] args) throws IOException {

String filename = "DeclarationOfIndependence.txt"; // Uses try-with to open the file

try (Scanner in = new Scanner(new File(filename))) {

// Read all the words in the file //declaring a Map to store all words and its count HashMap wordList = new HashMap<>(); // adding all words into map while (in.hasNext()) { String word = in.next(); if(wordList.containsKey(word)){ wordList.put(word, wordList.get(word) + 1); // incrementing count }else{ wordList.put(word, 1); } }

// now iterating through map and checking non-repeating words for(Map.Entry entry : wordList.entrySet()){ // if count is 1 and size is <=4, then print if( entry.getValue() == 1 && entry.getKey().length() <= 4) System.out.println(entry.getKey()); }

} } }

how will I change it too look for the word the instead of a word with a length of 1 to 3

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!