Computer Science 523
Advanced Programming

Summer 2014, The College of Saint Rose

NameAndTown BlueJ Project

Click here to download a BlueJ project for NameAndTown.


NameAndTown Source Code

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


NameAndTown.java

/*
 * Example NameAndTown: demonstrates the String's .length method and uses
 * an if/else if/else construct.
 *
 * Jim Teresco, The College of Saint Rose, CSC 202, Fall 2012
 *
 * $Id: NameAndTown.java 2366 2014-05-20 02:33:22Z terescoj $
 */

import javax.swing.JOptionPane;

public class NameAndTown {

    public static void main(String[] args) {
    
        // input dialogs to get name and hometown.
        String name = JOptionPane.showInputDialog("What's your name?");
        String town = JOptionPane.showInputDialog("What's your hometown?");
        
        // now, we print one of three messages, depending on whether
        // the name entered is longer, shorter, or the same length
        // as the hometown entered.
        
        // To do this, we use a method of the String class called length.
        // It returns the number of characters in the String.
        if (name.length() < town.length()) {
            JOptionPane.showMessageDialog(null,
                "Your name, " + name + " (length " + name.length() + 
                "), is shorter than your hometown, " + town + 
                " (length " + town.length() + ").");
        }
        else if (name.length() > town.length()) {
            JOptionPane.showMessageDialog(null,
                "Your name, " + name + " (length " + name.length() + 
                "), is longer than your hometown, " + town + 
                " (length " + town.length() + ").");            
        }
        else {
            // they must be the same length if I get here
            JOptionPane.showMessageDialog(null,
                "Your name, " + name + ", and hometown, " + town + 
                ", have the same length (" + name.length() + ")");
        }
    }
}