Answer to Question #278194 in Java | JSP | JSF for lemhs

Question #278194

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.


1
Expert's answer
2021-12-11T01:58:48-0500
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]);
  }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS