Shortest Word

Find the shortest word in a sentence.

JavaBeginner
Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        String s = sc.nextLine().trim();

        if (s.isEmpty()) {
            System.out.println("No words");
            return;
        }

        String[] words = s.split("\\s+");
        String shortest = words[0];
        for (String w : words) {
            if (w.length() < shortest.length()) {
                shortest = w;
            }
        }
        System.out.println("Shortest word: " + shortest);
        sc.close();
    }
}

Output

Enter a sentence: Java is fun
Shortest word: is

We initialize with first word and minimize by length.