Java - 如何使用 trim() 方法将空格转换为另一个字符串?

Java - How to convert blank spaces into another string using trim() method?

我无法弄清楚如何让程序拒绝仅包含空格的输入并使用 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 (n.trim() != "") if 语句的行为可能不是您所期望的。您应该改用:if (n.trim().equals("")).