24.2k views
3 votes
In java Please

3.28 LAB: Name format
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, firstInitial.middleInitial.

Ex: If the input is:

Pat Silly Doe
the output is:

Doe, P.S.
If the input has the form:

firstName lastName

the output is:

lastName, firstInitial.

Ex: If the input is:

Julia Clark
the output is:

Clark, J.

1 Answer

4 votes

Answer:

Step-by-step explanation:

import java.util.Scanner;

public class NameFormat {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter a name: ");

String firstName = input.next();

String middleName = input.next();

String lastName = input.next();

if (middleName.equals("")) {

System.out.println(lastName + ", " + firstName.charAt(0) + ".");

} else {

System.out.println(lastName + ", " + firstName.charAt(0) + "." + middleName.charAt(0) + ".");

}

}

}

In this program, we use Scanner to read the input name consisting of the first name, middle name, and last name. Based on the presence or absence of the middle name, we format the output accordingly using if-else statements and string concatenation.

Make sure to save the program with the filename "NameFormat.java" and compile and run it using a Java compiler or IDE.

User OscarLar
by
8.4k points