-4

I'm making a class involving objects. I'm having trouble with the retrieveMessage method, because when I test it, it returns a NullPointerException.

public class PostOffice 
   {
      public PostOffice(int size)
      {
         boxbox = new Letter[size];
      }
      public boolean placeLetter(Letter mail, int boxNum)
      {
         if(((boxNum>(boxbox.length-1))||(boxNum<0))||(boxbox[boxNum]!=null))
            return false;
         else{
            boxbox[boxNum]=mail;
            return true;
         }
      }
   /**Returns the message contained within the Letter located in the specific box number.
    * Returns "Empty!" if the post office box specified by the integer does not contain a Letter.
    * Returns "Box does not exist!" if there is no box with the specified integer.
    * @param boxNum The post office box number to be checked.
    */
      public String retrieveMsg(int boxNum)
      {
            if(boxNum<=boxbox.length-1)
            {
                String swag = boxbox[boxNum].getMsg();
                if(swag!=null && swag.isEmpty()==false)
                {
                    return swag;
                }
                return "Empty!";
            }
            return "Box does not exist!";
        }
      public Letter findSender(String name)
      {
         String sender;
         int index =0;
         for(int i = 0; i<boxbox.length; i++)
         {
            if((boxbox[i].getSender()).equals(name)){
               index= i;
            }
            else{
               return null;
            }
         }
         return boxbox[index];
      }
   }
5
  • Please post your stack trace.
    – Naman Gala
    Nov 26, 2014 at 12:53
  • What's null? Where's your stack trace? Tell us which line it appears on? Nov 26, 2014 at 12:54
  • 2
    NullPointerException is probably the easiest of all Java exceptions to debug. Learn how to debug. Start by actually reading the exception information you get.
    – Hot Licks
    Nov 26, 2014 at 12:54
  • 1
    Tyy changing if(boxNum<=boxbox.length-1) into if(boxNum<=boxbox.length-1 && boxbox[boxNum]!=null)
    – Michal
    Nov 26, 2014 at 12:54
  • possible duplicate of What is a Null Pointer Exception, and how do I fix it?
    – Kenster
    Nov 26, 2014 at 14:27

1 Answer 1

2

I guess the NullPointerException is thrown on this line :

String swag = boxbox[boxNum].getMsg();

When created, boxbox have size values, all of them are null.

You should first check if boxbox[boxNum] is null or not. If it is, it means that the post box does not contain a letter.

Not the answer you're looking for? Browse other questions tagged or ask your own question.