Write a method called wordLengths that accepts a string for the name of a file a
ID: 3796925 • Letter: W
Question
Write a method called wordLengths that accepts a string for the name of a file as a parameter. Your method should open the given file, count the number of letters in every token in the file, and then output a result diagram of how many words contain each number of letters. For example consider a file containing the following text. Four score and seven years ago This is a different line some Numbers 1 12 13 14 More Data Your method should produce the following output to the console: 1: ** 2: **** 3: ** 4. ****** 5. *** 6: 0 7: * 8: 0 9: * 10: 0 You can create your own sample text files, for testing purposes, but make sure they work correctly. You may assume that no token will have more than 20 characters.Explanation / Answer
WordLengthTest.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;
public class WordLengthTest {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the file name: ");
String fileName = scan.next();
wordLengths(fileName);
}
public static void wordLengths(String fileName) throws FileNotFoundException{
Scanner scan = new Scanner(new File(fileName));
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
String word;
int max = 0;
while(scan.hasNext()){
word = scan.next();
System.out.println(word);
if(max < word.length()){
max = word.length();
}
if(map.containsKey(word.length())){
map.put(word.length(), map.get(word.length())+1);
}
else{
map.put(word.length(), 1);
}
}
for(int i=1; i<=max; i++){
System.out.print(i+": ");
if(map.get(i)!=null){
for(int j=0; j<map.get(i); j++){
System.out.print("*");
}
}
else{
System.out.print("0");
}
System.out.println();
}
}
}
Output:
Enter the file name:
D:\input.txt
This
is
a
different
lin
some
Numbers
1
12
13
14
More
Data
1: **
2: ****
3: *
4: ****
5: 0
6: 0
7: *
8: 0
9: *
input.txt
This is a different lin
some Numbers 1 12 13 14
More Data
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.