Finding the Longest Word in Java GUI

In this tutorial, we will create a program that finds and display the longest word inputted in Java with GUI form. Now, let's start this tutorial! 1. Open JCreator or NetBeans and make a java program with a file name of longestWord.java. 2. Import javax.swing package. Hence we will use a GUI (Graphical User Interface) here like the inputting the words.
  1. import javax.swing.*;
3. Declare your variables; variable word as string that holds the next input word and longest as string which holds the longest word that has been found so far. Start with "".
  1. String word;          
  2. String longest = "";
4. Create a loop reading words until the user clicks CANCEL that will exit if Cancel or close box clicked.
  1.         while (true) {
  2.             word = JOptionPane.showInputDialog(null, "Enter a word or CANCEL.");
  3.             if (word == null) break;  
5. Create an If statement that the length of the inputted word is greater than the longest word length then it will be equal so that it will check to see if this words is longer than longest so far.
  1. if (word.length() > longest.length()) {
  2.                 longest = word;  // Remember this as the longest.
  3.             }  
6. Lastly, display the longest word as an output using JOptionPane.showMessageDialog.
  1. JOptionPane.showMessageDialog(null, "The longest word was " + longest);
Output: output Hope this helps! :) Best Regards, IT Instructor/System Developer/Android Developer/Freelance Programmer If you have some queries, feel free to contact the number or e-mail below. Mobile: 09488225971 Landline: 826-9296 E-mail:[email protected] Visit and like my page on Facebook at: https://www.facebook.com/BermzISware Add and Follow me on Facebook: https://www.facebook.com/donzzsky

Add new comment