For this assignment, we’ve invented a new format for storing names. It has three
ID: 3637715 • Letter: F
Question
For this assignment, we’ve invented a new format for storing names. It has three sections for the last name, first name, and middle name. There is a colon between the first two sections and a comma between the second two. The last name part can include modifiers like “Jr.” or “Sr.” and the first name part can include titles like “Mr.” and “Dr.”. If a field is empty, then you still use the separators.Write a program that can read a line with a name stored in this format. Your program will then print the name in "First Middle Last" format. Notice that you can’t just look for the first comma in the line in order to find the second separator character.
Your program must use the Java String class functions, "substring" and "indexOf". "substring" and "indexOf" are described in your book and are documented on this Web page: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html
Sample runs:
Name Rearranging Program
Enter a name in our format:
Hall:Dame Professor Wendy,
The name is: Dame Professor Wendy Hall
Name Rearranging Program
Enter a name in our format:
Kennedy, Jr.:John,F.
The name is: John F. Kennedy, Jr.
Name Rearranging Program
Enter a name in our format:
Bulterman:Dick,c a
The name is: Dick c a Bulterman
Explanation / Answer
package stringoperations;
import java.util.Scanner;
public class StringOperations {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
String fullName;
String firstName;
String middleName;
String lastName;
int colonIndex;
int lastCommaIndex;
//get formatted fullName from user
System.out.println("Name Rearranging Program ");
System.out.println("Enter a name in our format:");
fullName = scanner.nextLine();
//find the index of the separators
colonIndex = fullName.indexOf(':');
lastCommaIndex = fullName.indexOf(',', colonIndex);
//use substring to split up first, middle, and last name
firstName = fullName.substring(colonIndex + 1, lastCommaIndex);
middleName = fullName.substring(lastCommaIndex + 1);
lastName = fullName.substring(0, colonIndex);
//print out the name in "First Middle Last" format
System.out.print(" The name is: " + firstName);
if (firstName.compareTo("") != 0) { //to avoid print an extra space char in case firstName is blank
System.out.print(" ");
}
System.out.print(middleName);
if (middleName.compareTo("") != 0) { //to avoid print an extra space char in case middleName is blank
System.out.print(" ");
}
System.out.println(lastName);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.