Shortest Word in Java
Find the shortest word in a sentence.
BeginnerModule 4: String ProgramsExample 12 of 25
shortest-word.java
1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Enter a sentence: ");7 String s = sc.nextLine().trim();89 if (s.isEmpty()) {10 System.out.println("No words");11 return;12 }1314 String[] words = s.split("\\s+");15 String shortest = words[0];16 for (String w : words) {17 if (w.length() < shortest.length()) {18 shortest = w;19 }20 }21 System.out.println("Shortest word: " + shortest);22 sc.close();23 }24}
Output
Enter a sentence: Java is fun Shortest word: is
What's going on
We initialize with first word and minimize by length.