Going through a book, I encountered the following assignment:
Write an application that asks for the user’s first, middle, and last names and replies with the user’s initials.
Are there any flaws you notice immediately? Is there any way this code can be improved? I'm not really interested in coding style (I guess someone is going to say that I should put those braces on the next line, but I like it this way).
import javax.swing.JOptionPane;
public class Program
{
private static String fullName;
private static String firstName;
private static String middleName;
private static String lastName;
private static char firstInitial;
private static char middleInitial;
private static char lastInitial;
public static void main(String[] args)
{
start();
}
public static void start()
{
greet();
askInput();
seperateFullName(fullName);
getInitials(firstName, middleName, lastName);
showResult();
}
// @formatter:off
private static void greet()
{
int dialogResult = JOptionPane.showConfirmDialog(null, "This program asks you for you first, middle and last name"
+ " and gives back your initials.\nDo you want to continue?");
if (dialogResult == JOptionPane.NO_OPTION)
{
JOptionPane.showMessageDialog(null, "Shutting down...", null, JOptionPane.WARNING_MESSAGE);
System.exit(0);
}
}
private static void askInput()
{
fullName = JOptionPane.showInputDialog("Please enter your first, middle and last name.");
}
private static void seperateFullName(String fullName)
{
try
{
int firstSpace = fullName.indexOf(" ");
firstName = fullName.substring(0, firstSpace);
int lastSpace = fullName.lastIndexOf(" ");
middleName = fullName.substring(firstSpace + 1 , lastSpace);
lastName = fullName.substring(lastSpace + 1, fullName.length());
}
catch (StringIndexOutOfBoundsException e)
{
JOptionPane.showMessageDialog(null, "Invalid input!", null,
JOptionPane.WARNING_MESSAGE, null);
start();
}
}
private static void getInitials(String firstName, String middleName, String lastName)
{
firstInitial = firstName.charAt(0);
middleInitial = middleName.charAt(0);
lastInitial = lastName.charAt(0);
}
// @formatter:on
private static void showResult()
{
JOptionPane.showMessageDialog(null, "Your initials are: "
+ firstInitial + "." + middleInitial + "." + lastInitial + ".");
}
}