Question
Java Question. Read all words from a file and group them by length. Print out how many words of each length are in the file.
Java Question. Read all words from a file and group them by length. Print out how many words of each length are in the file. Use collect and Collectors.groupingBy. Here is the test.txt file.
There now is your insular city of the Manhattoes belted round by wharves as Indian isles by coral reefs commerce surrounds it with her surf Right and left the streets take you waterward Its extreme downtown is the battery where that noble mole is washed by waves and cooled by breezes which a few hours previous were out of sight of land Look at the crowds of water gazers there
I did the coding but I have an error. Please help me to fix it. My word count did not appear in result.
import java.io.IOException;
import java.io.File;
import java.util.Scanner;
import java.util.Comparator;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Stream;
import java.util.stream.Collectors;
/**
* Read all words in a file and group them by length. Print out
* how many words of each length are in the file. Use collect
* and Collectors.groupingBy.
*/
public class words
{
public static void main(String[] args) throws IOException
{
String filename = "test.txt";
Map
// Your work goes here
ArrayList
try (Scanner fileInput=new Scanner(new File("test.txt"));)
{
//read words from file
int count = 0;
while(fileInput.hasNextLine())
{
//count words
fileInput.next();
String s = line.next();
String w[] =s.split(" ");
String l[] = s.split(" ");
count +=w.length;
// add words to object
words.add(fileInput.next());
}
//display all words in file
System.out.println("All words are: ");
for(String current: words)
System.out.println(current);
// leave blank line
System.out.println();
//create stream
Stream
// call collect and pass the collecting by
Map
System.out.println("Result key value"+"pairs are");
//print each of the key value pairs
for(Map.Entry
System.out.println(current.getKey() +" "+current.getValue());
//count words
}
// Put your work above this line
System.out.println("Word counts in " + filename);
System.out.println(result);
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started