Computer Science 202
Introduction to Programming

Fall 2012, The College of Saint Rose

LongestWord BlueJ Project

Click here to download a BlueJ project for LongestWord.


LongestWord Source Code

The Java source code for LongestWord is below. Click on a file name to download it.


LongestWord.java


/**
 * Program to find the longest of a series of input words, including ties.
 * 
 * Jim Teresco, The College of Saint Rose, CSC 202, Fall 2012
 * 
 * $Id: LongestWord.java 1982 2012-11-13 15:27:16Z terescoj $
 */

import java.util.Scanner;

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

        final String SENTINEL = "done";
        int numWords = 0;
        String longestWord = "";
        int longestWordLength = 0;
        Scanner keyboard = new Scanner(System.in);
        String word;
        
        do {
            System.out.print("Please enter the next word (\"" + SENTINEL + "\" to end): ");
            word = keyboard.next();
            if (!word.equals(SENTINEL)) {
                // do we have a new winner?
                if (word.length() > longestWordLength) {
                    // new longest word
                    longestWord = word;
                    longestWordLength = longestWord.length();
                }
                else {
                    // is it a tie?
                    if (word.length() == longestWordLength) {
                        // it is a tie!
                        longestWord = longestWord + ", " + word;
                    }
                }
                numWords++;
            }
                
        } while (!word.equals(SENTINEL));
        
        if (numWords > 0) {
            System.out.println("You entered " + numWords + " words.");
            System.out.println("The longest word(s): " + longestWord);
        }
        else {
            System.out.println("No words!");
        }
    }
}