85.8k views
3 votes
Many documents use a specific format for a person's name. Write a program whose input is: firstName middleName lastName and whose output is: lastName, firstName middleInitial. Ex: If the input is: Pat Silly Doe the output is: Formatted Name: Doe, Pat S. If the input has the form firstName lastName, the output is lastName, firstName Ex: If the input is: Julia Clark the output is: Formatted Name: Clark, Julia If the input has any other form, then the output should be The input does not have the correct form

2 Answers

4 votes

Answer:

name = input(" Enter your Name:")

br = name.split()

def split(word):

return list(word)

word = br[1]

print(br[2],", ",br[0]," ",word[0])

Step-by-step explanation:

The Programming Language used is python.

The function used is called a split function, it allows the splitting of a string into a list of words and is the best method to accomplish this particular task.

Line 1:

name = input(" Enter your Name:")

initializes the string and prompts the person to input a name

Line 2:

br = name.split()

uses split() to break the string up into a list of words. with each slot having its unique identifier (index number) starting from 0.

Line 3, 4, 5 :

def split(word):

return list(word)

word = br[1]

- if the input as in your example is "Pat Silly Doe" what happens is that "Pat Silly Doe" is broken up into a list.

-we now have [Pat, Silly, Doe] and each of the elements in the list have their unique index.

Pat-0

Silly-1

Doe-2

Silly is split into individual characters [s,i,l,l,y]

Line 6:

print(br[2]," ",br[0]," ",word[0])

This prints out the names in the new format of:

br[2] --> Doe

br[0] --> Pat

word[0] --> s

Doe, Pat S

User Zare Ahmer
by
5.2k points
2 votes

Answer:

The code is given below in Java with appropriate comments

Step-by-step explanation:

//declaring the imports

import java.util.Scanner;

//class FormatName

public class FormatName {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

//inputing the names

System.out.print("Enter your name (first middle last): ");

String fullName = scanner.nextLine();

String[] names = fullName.split("\\s+");

//applying the formatting

if (names.length == 2) {

System.out.println("Formatted Name: " + names[1] + ", " + names[0]);

} else if (names.length == 3) {

System.out.println("Formatted Name: " + names[2] + ", " + names[0] + " " + names[1].charAt(0) + ".");

} else {

System.out.println("The input does not have correct form");

}

}

}

User Rodrigo Queiroz
by
4.8k points