In: Computer Science
Display the shortest words in a sentence in JAVA
Write a method that displays all the shortest words in a given sentence. You are not allowed to use array
In the main method, ask the user to enter a sentence and call the method above to display all the shortest words in a given sentence.
You must design the algorithms for both the programmer-defined method and the main method.
Program Code Screenshot :
Sample Output :
Program Code to Copy
import java.util.ArrayList; import java.util.List; import java.util.Scanner; class Main{ static void displayShortest(String s){ //Split the sentence String words[] = s.split(" "); //Initialize a new list to store shortest words List<String> shortest = new ArrayList<>(); //Initialize shortest words list int sl = Integer.MAX_VALUE; //Loop through all words for(String word : words){ //If length of the word is lower than shortest length obtained so far if(word.length()<sl){ //Create a new list and add shortest = new ArrayList<>(); sl = word.length(); shortest.add(word); } //If word length is same as the shortest length obtained, add to list else if(word.length()==sl){ shortest.add(word); } } //Print to console System.out.println("Shortest words are : "+shortest); } public static void main(String[] args) { System.out.println("Enter a sentence"); Scanner obj = new Scanner(System.in); String s = obj.nextLine(); displayShortest(s); } }