Programming and Problem Solving with Java

(やまだぃちぅ) #1

CASE STUDY^83


DISPLAY A NAME IN MULTIPLE FORMATS


Problem:You are beginning to work on a problem that needs to output names in several
formats. To start, you decide to write a short Java application that inputs a single name
and displays it in a variety of formats, so you can be certain that all of your string
expressions are correct.


Input:The name in three parts, as input via System.in:
First
Last
Middle Initial


Output:The input name in two formats:
First Last
Last, First, Middle Initial.


Discussion:You could easily just type the name in the two formats as string literals in
the code, but the purpose of this exercise is to develop and test the string expressions
you need for the larger problem. We also know that a Nameis an object in that problem,
so we should develop such an object from the beginning.
Because you plan to use the same expressions in the full application, you decide that
this preliminary application should implement a Nameclass that provides a constructor
to input the name as well as value-returning methods that provide the name in the two
formats. Then you can reuse the class in the full application, which will keep this appli-
cation very simple.
A name consists of three parts: first name, last name, and middle initial. These parts
become the fields in the class. Here is the algorithmic solution:


As we noted in our earlier discussion, three methods are associated with this class: a
constructor and two value-returning methods. Let’s look first at the constructor. We
know that it must be called Name. Its job is to input the name from System.in. To do so, it
must first instantiate a BufferedReader, then prompt for input of each of the three parts
and read each part via the BufferedReader.


Define Fields
String first
String last
String middle
Free download pdf