Computer Science 202
Introduction to Programming
Fall 2012, The College of Saint Rose
NameAndTown BlueJ Project
Click here to download a BlueJ project for NameAndTown.
Download file: NameAndTown.vls
NameAndTown Source Code
The Java source code for NameAndTown is below. Click on a file name to download it.
/*
* 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 1914 2012-09-25 03:05:03Z 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() + ")");
}
}
}