Programming and Problem Solving with Java

(やまだぃちぅ) #1

CASE STUDY^85


String last; // Person’s last name
String middle; // Person’s middle initial

publicName() throwsIOException // Gets a name from System.in
{
BufferedReader in; // Input stream for strings
// Instantiate in using System.in
in = newBufferedReader(newInputStreamReader(System.in));
System.out.print(“Enter first name: “); // Prompt for first name
first = in.readLine(); // Get first name
System.out.print(“Enter last name: “); // Prompt for last name
last = in.readLine(); // Get last name
System.out.print(“Enter middle initial: “); // Prompt for middle initial
middle = in.readLine(); // Get middle initial
}

publicString firstLastFormat () // Returns name in first-last format
{
returnfirst + “ “+ last;
}

publicString lastFirstMiddleFormat() // Returns name as last, first, m.
{
returnlast + “, “+ first + “, “+ middle + “.”;
}
} // End of Name Class

// Driver for testing Name class
public static voidmain(String[] args) throwsIOException
{
Name testName; // Declare a name
testName = newName(); // Instantiate a name
System.out.println(“Name in first-last format is “+
testName.firstLastFormat()); // First format
System.out.println(“Name in last-first-initial format is “+
testName.lastFirstMiddleFormat()); // Second format
}
}


The output from the program follows:
Free download pdf