Question: Not entirely sure why after running my code, the smallest word and largest word are repeating null. Is there a way to remove it? Below
Not entirely sure why after running my code, the smallest word and largest word are repeating null. Is there a way to remove it?
Below is the code:
import java.util.*;
public class PhraseAnalyzer { private String phrase; private String[] words; private boolean isValid; public PhraseAnalyzer(String phrase) { this.phrase = phrase; this.words = getWords(); this.isValid = isValidPhrase(); } private String[] getWords() { // split the phrase into words using whitespace as a delimiter return phrase.split("\\s+"); } private boolean isValidPhrase() { for (String word : words) { // check if the word contains only letters and ends with a punctuation mark if (!word.matches("[a-zA-Z]+[.,;:?!]*$")) { System.out.println("Phrase is not valid. Terminating."); System.exit(1); } } return words.length > 0; } public String[] getWordsArray() { return words; } public String[] getSmallestWords() { if (!isValid) { System.out.println("Phrase is not valid. Terminating."); System.exit(1); } Arrays.sort(words, Comparator.comparing(String::length)); return Arrays.copyOfRange(words, 0, 5); } public String[] getLargestWords() { if (!isValid) { System.out.println("Phrase is not valid. Terminating."); System.exit(1); } Arrays.sort(words, Comparator.comparing(String::length).reversed()); return Arrays.copyOfRange(words, 0, 5); } public double getAverageWordLength() { if (!isValid) { System.out.println("Phrase is not valid. Terminating."); System.exit(1); } int totalLength = 0; for (String word : words) { totalLength += word.length(); } return (double) totalLength / words.length; } public Map
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
