0

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?

VGSO15
  • 15
  • 3

1 Answers1

0

The behavior of the if statement, if (n.trim() != ""), is probably not what you are expecting. You should instead use: if (n.trim().equals("")).

sery
  • 186
  • 2
  • 3
  • 1
    Welcome to Stack Overflow - the question you've answered here is a very common one, so it's been closed as a duplicate of another Q&A where the same thing is explained. I recommend reading the help page https://stackoverflow.com/help/how-to-answer - in particular *"Not all questions can or should be answered here. Save yourself some frustration and avoid trying to answer questions which... ...have already been asked and answered many times before."* – kaya3 Feb 27 '20 at 21:53