Java Programming: Initials v2
Write a program that asks for a first and last name, separated by a blank, and displays the initials.
- Ask the user for their first and last names.
- Read the complete name and save it in a String variable.
Use either
in.readLine()
orJOptionPane.showInputDialog(...)
. - Use the
substring(...)
method to get character 0 for the first initial. - Use
indexOf(" ")
to find where the blank is. Remember that character position in an int variable. - Use
substring(...)
again to get the character after the blank (ie, first character from the last name). UsetoUpperCase()
to convert the initials to upper case. - Display the initials to the user.
String or char?
When you are working with a single character, you can use either a char
variable, or a String with a single character in it. I recommend using String for
this program.
If you were doing a huge amount of computation -- processing hundreds of thousands of names,
it would be more efficient to use charAt(...)
because it's more
efficient to use a primitive type than an object type.
On the other hand, substring(...)
has the simplicity
of working with only one type (String
).