我无法弄清楚如何让程序拒绝仅包含空格的输入并使用 trim() 方法将其更改为字符串“N/A”。我也尝试使用 replaceAll() 方法,但它们也不起作用。
这是程序:
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());
}
}
名称的输出将保持空白,而不是更改为字符串“N/A”
有谁知道如何解决这一问题?
if 语句的行为 if (n.trim() != "") 可能不是您所期望的。你应该使用:if (n.trim().equals(""))。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句