import java.util.Scanner; /** This is a Java application that, given as input a name in the form ** ** ** ** (where each of the names is a non-empty sequence of non-space characters ** and where whitespace (space, tab, or newline characters) is used for ** separating the components of the name), produces as output the same ** name, but converted into the form ** ** , . ** ** For example, provided as input ** ** "Mary Barbara Smith" ** ** the program will produce as output ** ** "Smith, Mary B." ** ** This version of the program illustrates how to use a Scanner object ** to parse the input data (rather than searching for spaces using ** String's indexOf() method). The result is a more robust program ** in that it produces the desired result even when the input string has ** "extra" spaces in it. ** ** Author: R. McCloskey, Sept. 2013 */ public class NameConversionViaScanner { public static void main(String[] args) { // Declare symbolic constants for special characters. final char SPACE = ' '; final char COMMA = ','; final char PERIOD = '.'; final char DOLLAR_SIGN = '$'; // Create a Scanner that interprets input entered on the keyboard. Scanner keyboard = new Scanner(System.in); // Prompt the user to enter a name. System.out.print("Enter name (in format ): "); // Read the user's response into a String. String name = keyboard.nextLine(); // create a Scanner object that "reads from" the string referred // to by the 'name' variable. Scanner nameScanner = new Scanner(name); // The components of the name correspond to three "tokens"; read them. String firstName = nameScanner.next(); String middleName = nameScanner.next(); String lastName = nameScanner.next(); // The middle initial is the zero-th character of middleName char midInit = middleName.charAt(0); // The string to be produced as output is obtained by concatenating // lastName, comma, etc., etc. String outName = lastName + COMMA + SPACE + firstName + SPACE + midInit + PERIOD; // Print a message that reports the input and output names. Dollar // signs are shown on either side of each name for the purpose of // showing any leading and/or trailing spaces. System.out.println("Input name: " + DOLLAR_SIGN + name + DOLLAR_SIGN); System.out.println("Output name: " + DOLLAR_SIGN + outName + DOLLAR_SIGN); } }