Write a method called wordLengths that accepts a string for
Solution
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

