Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java Programming: Complete the following program: import java.util.Scanner; impo

ID: 3686171 • Letter: J

Question

Java Programming:

Complete the following program:

import java.util.Scanner;

import java.util.stream.Collectors;


/** * 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 PrintDistinctShortWords {

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

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

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

// Read all the words in the file

List wordList = new ArrayList<>();

while (in.hasNext()) {

wordList.add(in.next());

}


// Turn the wordList into a stream of words

// modify the following line to print all the distinct words in the stream that have at most four letters (in some order). You may modify other statements.

wordList.stream();

}
}
}

Explanation / Answer

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 PrintDistinctShortWords {

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

       String filename = "test.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<String,Integer> 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<String, Integer> 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());
           }

       }
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote