Home Java Java-tips Data Strings Q-pr-string-if Programming - Transform Name

Ask Questions?

View Latest Questions



Programming - Transform Name
Posted on: July 26, 2006 at 12:00 AM
Write a program to redisplay a name, possibly transformed

Java: Programming - Transform Name

Write a program to redisplay a name, possibly transformed

This Java program will reformat a user's name. There are two cases that have to be handled: the trivial case of a single name, where the name doesn't have to be changed, and the case where the names must be rearranged.

Case 1 - Single name

If the user enters only one name, eg, Madonna, or Prince, display that name without changes.

   Input:  Madonna
   Output: Madonna

Case 2 - Change First Last into Last, First

If the name consists of a first and last name separated by a blank, you must transform it. For example,

   Input:   Michael Maus
   Output:  Maus, Michael

Using the String methods, transform this string into the last name, comma, first name format. Some useful string methods are indexOf and substring.

Iterative programming

A programming style that is extremely useful is called iterative programming. In this style you write a little bit of the program and run it. For example, start this with a program that does nothing in main. After that compiles and runs (and does nothing), add Java statements that read the input string (but don't do anything with it yet. Continue in this way with very small steps.

In this problem you will probably want to do the single name case first. When that is running you try the other, which requires an if statement and string methods.

Extra credit (sort of)

I don't allow more than the maximum score on a problem, however if you do extra work, it can cancel out points that were taken off for other reasons.

Capitalizing the names would be good extra credit for this program. You can easily use the Java functions to change the case to something standard.

   Input:   mIcHaEl mAuS
   Output   Maus, Michael


You may use JOptionPane.showInputDialog(...), Scanner.nextLine(), or SavitchIn.readLine(). You must read both names together; you can't ask for the first and last names separately.