CS 201 - Computer Science I - Fall 2008
Strings


Loyola College > Department of Computer Science > Dr. James Glenn > CS 201 > Examples and Lecture Notes > Strings

UsernameGenerator.java

import java.util.Scanner;

/**
 * Reads a name on one line of text from standard input (usually the
 * keyboard) and displays the username constructed from the first
 * initial, middle initial, and last name of the name, truncated to
 * ten characters.  The input must be in the form "First Middle Last".
 * We can handle some special cases with lastIndexOf or clever uses of
 * Math.max and Math.min, but arbitrary cases will require the use of
 * selection statements.
 *
 * @author Jim Glenn
 * @version 0.1 9/17/2008
 */

public class UsernameGenerator
{
    public static void main(String[] args)
    {
	final int LONGEST_USERNAME = 10;

	// create a scanner to read input from keyboard

	Scanner scan = new Scanner(System.in);

	// prompt user for name and read it

	System.out.println("Please enter a name (first middle last):");
	String fullName = scan.nextLine();

	// find first initial

	char firstInitial = fullName.charAt(0);

	// find middle name and get initial -- middle name is after 1st space

	int middleIndex = fullName.indexOf(' ') + 1;
	char middleInitial = fullName.charAt(middleIndex);

	// find last name and extract it -- it starts after 1st space
	// after middle name and goes to end of input

	int lastIndex = fullName.indexOf(' ', middleIndex) + 1;
	String lastName = fullName.substring(lastIndex);

	// merge parts together -- since + between chars works funny
	// we convert the single chars to Strings before gluing things
	// together (we could have just used Strings and substring
	// for firstInitial and middleInitial in the first place instead
	// of chars and charAt)

	String username = (String.valueOf(firstInitial)
			   + String.valueOf(middleInitial)
			   + lastName);

	// convert to lower case

	username = username.toLowerCase();

	// figure out how many characters to keep and truncate

	int finalLength = Math.min(LONGEST_USERNAME, username.length());
	username = username.substring(0, finalLength);

	// display result

	System.out.println(username);
    }
}
This code can also be downloaded from the file
UsernameGenerator.java.