开发者

question with returning an accessor method

开发者 https://www.devze.com 2022-12-21 10:50 出处:网络
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?

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 开发者_如何学GolastName)
    {
        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;
    }
}


 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.


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.


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

last.substring(0,1).toUpperCase() + last.substring(1).toLowercase()
0

精彩评论

暂无评论...
验证码 换一张
取 消