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 a single space occurs on either side of the middle 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." */ public class NameConversion { 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(); // Determine the position of the space in between first and middle names. int posOfFirstSpace = name.indexOf(SPACE); // The first name is the prefix ending at the position preceding // the first occurrence of a space. String firstName = name.substring(0, posOfFirstSpace); // The middle initial is the character at the position immediately // following the first occurrence of a space. char midInit = name.charAt(posOfFirstSpace + 1); // The last name is the suffix beginning at the position immediately // following the last occurrence of a space. String lastName = name.substring(name.lastIndexOf(SPACE)+1, name.length()); // Note: Rather than finding the position of the last occurrence of a // space (as we did by using lastIndex() above), we instead could have // found the position of the second occurrence of a space by using // indexOf() as follows: name.indexOf(SPACE, posOfFirstSpace+1) // 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 // verifying that no leading or trailing spaces exist within them. System.out.println("Input name: " + DOLLAR_SIGN + name + DOLLAR_SIGN); System.out.println("Output name: " + DOLLAR_SIGN + outName + DOLLAR_SIGN); } }