简体   繁体   中英

Assigning to a variable if string is null

I have a code that sets the instance variables name, although if the user enters null the name should appear as "Unknown" I am unable to think of how to do this, please check out my code and help me with how I am going about it wrong. Thanks!

My code:

  if (name.equals(null))
    {
        this.name = name;
        name="Unknown";
    }
    else
    {
        this.name=name;
    }

If user enters null it has to be checked with "null" String, like below. Have added few more checks.

if (name == null || "".equals(name.trim()) || "null".equals(name)) {
        this.name = name;
        this.name="Unknown";
} else {
        this.name=name;
}
if (name.equals("null"))
{
   name = "Unknown";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM