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

Ask Questions?

View Latest Questions

Advertisement


 
 

Programming: Initials 1
Posted on: July 26, 2006 at 12:00 AM
Write a program that asks for names and displays the initials.

Java: Programming: Initials 1

Name ________________________________________

Write a program that asks for names and displays the initials.

  1. Ask the user for their first name. Save it in a string variable.
  2. Ask the user for their last name. Save it in a string variable.
  3. Use the substring() method to get the first characters from both the first and last names. Use the toUpperCase() method to convert them to upper case.
  4. Display the initials to the user.

Discussion

What you need is the first letter of each name. There are two ways to get it.

  1. substring(...). You can use the substring(...) method to get a one-character substring starting at the beginning of the name. You can then concatenate this to the first letter from the other name.
  2. charAt(...) Strings are made up of characters (primitive type char). You can extract the first character with charAt(...) and proceed pretty much as above.

Which to use? They are both reasonable solutions. If you were doing a huge amount of computation -- processing hundreds of thousands of names, it would be more efficient to use the charAt(...) solution because it's more efficient to use a primitive type than an object type. On the other hand, the substring(...) solution has the simplicity of working with only one type (String). Use either one.

Copyleft 2005 Fred Swartz MIT License
Advertisement


DMCA.com