Java Notes Prev: Java Example: Dialog: Capitalize

Java Example: Dialog: Longest Word

See Dialog Input Loop for how to read in a loop using dialog boxes.

Java Example: Longest Word

This program displays the longest word that was entered.

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
// File   : loops/LongestWord.java
// Purpose: Display the longest word that was entered.
//          Reads until user clicks CANCEL / close box..
// Author : Fred Swartz
// Date   : 2005 Oct 19

import javax.swing.*;

public class LongestWord {
    public static void main(String[] args) {

        //... Local variables
        String word;          // Holds the next input word.
        String longest = "";  // Holds the longest word that has
                              //    been found so far.  Start with "".

        //... Loop reading words until the user clicks CANCEL.
        while (true) {
            word = JOptionPane.showInputDialog(null, "Enter a word or CANCEL.");
            if (word == null) break;   // Exit if Cancel or close box clicked.

            //... Check to see if this words is longer than longest so far.
            if (word.length() > longest.length()) {
                longest = word;  // Remember this as the longest.
            }
        }

        //... Output the longest word.
        JOptionPane.showMessageDialog(null, "The longest word was " + longest);
    }
}