The file dictionary.txt is a "dictionary" file containing a long list of words. Write a Java program to report the following information:
a. the number of words in the file,
b. the average number of letters per word,
c. the longest word and its length (if there is more than one word of greatest length, you only need to report one of them),
d. the shortest word and its length (if there is more than one word of least length, you only need to report one of them),
e. the first word in the file,
f. and the last word in the file.
public class Dictionary {
public static void main(String[] args) {
List<String> dict = Files.getAllLines(Paths.get("dictionary.txt"));
StringBuilder builder = new StringBuilder();
for (String line : dict) {
builder.append(line);
}
String text = builder.toString().replaceAll(".", "").replaceAll(",", "");
String words = text.split("\\s++");
System.out.printf("Number of words: %d\n", words.length);
int letters = 0;
for (int i = 0; i < words.length; i++) {
letters += words[i].size();
}
System.out.printf("Average number of letters per word: %d\f\n", 1.0f * letters / words.length);
String longest = words[0], shortest = words[0];
for (int i = 0; i < words.length; i++) {
if (longest.size() < words[i].size()) longest = words[i];
if (shortest.size() > words[i].size()) shortest = words[i];
}
System.out.printf("Longest word and its length: %s, %d\n", longest, longest.size());;
System.out.printf("Shortest word and its length: %s, %d\n", shortest , shortest.size());
System.out.printf("First word in the file: %s\n", words[0]);
System.out.printf("Last word in the file: %s\n", words[words.size()-1]);
}
}
Comments
Leave a comment