views:

59

answers:

3

How would I get the accessor method to return the first letter of a name to be uppercase and the rest in lowercase no matter what was entered?

public class Name
{
    private String first;
    private String last;

    /**
     * Constructor for objects of class Name
     */
    public Name(String firstName, String lastName)
    {
        first = firstName;
        last = lastName;
    }

    /**
     * @returns firstName
     */ 
    public String getFirstname()
    {
        return first;       
    }

    /**
     * @returns lastName
     */ 
    public String getLastname()
    {
        return last;  
    }

    /**
     * @returns Fullname
     */ 
    public String getFullname()
    {
        return first + last;
    }

    /**
     * @para new firstname
     */
    public void setFirstname(String firstName)
    {
        first = firstName;
    }
}
A: 

This is the only way I can really think of doing it:

last.substring(0,1).toUpperCase() + last.substring(1).toLowercase()
charlie
It fails on an empty string.
Ravi Wallau
And on surrogate pairs. (This is for people with unusual names.)
Tom Hawtin - tackline
Also fails on `null` (which isn't checked for in construction).
Tom Hawtin - tackline
A: 

Use StringUtils.capitalize from Commons Lang.

Always use the library if it is available, they probably went through all the corner cases that you would only figure out after solving bug after bug.

Ravi Wallau
But that doesn't ensure that the rest of the name is lower case; it just capitalizes the first and leaves the rest as they are. The OP said "and the rest in lowercase no matter what was entered"
charlie
+1  A: 
 public static String capitalizeFirst(String s) {
   return Character.toUpperCase(s.charAt(0)) + s.substring(1).toLowerCase();
 }

 public String getFirstname() {
    return capitalizeFirst(first);
 }

As the name implies, capitalizeFirst capitalizes the first character of a non-empty string, and converts the rest of the string to lowercase.

polygenelubricants