I am having trouble figuring out how to ge the program to reject inputs that contain only white spaces and changing it into the string "N/A" with the trim() method. I have also tried to use the replaceAll() methods, but they aren't working either.
Here is the program:
public class Object1
{
//attributes
private String name;
//symbolic constant
private final String NA = "N/A";
// getter/setter methods for name
public void setName(String n)
{
if (n.trim() != "")
name = n.trim();
else
name = NA;
}
public String getName()
{
return name.trim();
}
public Object1()
{
name = NA;
}
}
public class Object2
{
public static void main(String[] args)
{
// create object
Object1 x;
x = new Object1();
// the name of the object
a.setName(" ");
// report the name of the object
System.out.println("The name of the object is: " + x.getName());
}
}
The output for the name would remain blank instead of changing into the string "N/A"
Does anyone know how to fix this?
The behavior of the if statement, if (n.trim() != ""), is probably not what you are expecting. You should instead use: if (n.trim().equals("")).