Home Java Java-tips Data Strings Q-pr-string-if Programming: Initials 2

Ask Questions?

View Latest Questions

Advertisement


 
 

Programming: Initials 2
Posted on: July 26, 2006 at 12:00 AM
Write a program that asks for a name, including both first and last name, and displays the initials.

Java: Programming: Initials 2

Name ________________________________________

Overview. Write a program that asks for a name, including both first and last name, and displays the initials. You should also handle the case when the user enters a single name (eg, Prince).

New Java features. The purpose of this exercise is to use the if statement as well as more Java String methods.

  1. Input. Ask the user for their first and last name, separated by a blank. Trim blanks from the front and back and save it in a string variable.
  2. Separate names. Use the indexOf() or lastIndexOf() to find the blank separating the names. You can then use substring() to extract the first and last initials and store them in variables.
  3. Single name? If the user entered only one name, you should only produce a single initial. Test the result of indexOf() to see if there was a blank. If there was no blank, you can assume it was a single name.
  4. Output. Display the initial(s) in upper case.

Extra, cancellation, credit. You can't get more than the maximum credit for this exercise, but you can add extra features. Adding something extra can cancel out points you may lose in the main part of the problem.

No input? A good extra credit extension to this program would be to check if there was any input. If the user entered no characters, the length of the input string will be zero and you can check for that. If there was no input, display an error message, but don't try to output any initials of course. Soon you'll learn how to use loops to go back and ask for more input, but don't try that on this program yet.

Copyleft 2005 Fred Swartz MIT License
Advertisement


DMCA.com