Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

when I try to run it, it asks and allows me to enter the birth date, month and y

ID: 3636944 • Letter: W

Question

when I try to run it, it asks and allows me to enter the birth date, month and year, but as soon as i enter in the place it throws this:

Exception in thread "main" java.lang.NullPointerException

at Pet.setBirthInfo(Pet.java:26)

at Assignment4.main(Assignment4.java:61)

Where Pet.java:26 is: "birth.setDate(date);" and Assignment4.java:61 is: "pet1.setBirthInfo(date, month, year, place);"

I'm honestly not sure what i'm doing wrong; I've gone over the programs multiple times without any results.

 

 

(This is basically how my other parts of the program look...I'm having the same issue as this poster, but I can't figure it out...)
 http://www.java-forums.org/new-java/45269-unresolved-exceptions-my-program.html

 

 


public class Pet

{

private String petName, type;

private BirthInfo birth;



//Constructor to set default values

public Pet()

{

petName = "?";

type = "?";

}



//accessor methods

public String getPetName()

{

return petName;

}



public String getType()

{

return type;

}



public BirthInfo getBirthInfo()

{

return birth;

}


//modifier methods

public void setPetName(String pName)

{

petName = pName;

}



public void setType(String pType)

{

type = pType;

}



public void setBirthInfo(int date, int month, int year, String place)

{



birth.setDate(date);

birth.setMonth(month);

birth.setYear(year);

birth.setPlace(place);

}



public String toString()

{

return " Pet Name: " petName " Type: " type " Birth Information: " birth " ";

}

}



I know something is wrong in the setBirthInfo method but I don't know what...I was told that BirthInfo wasn't initialized or something...Please help!

Explanation / Answer

Yes the object birth of type BirthInfo needs to initialized. Try adding this line at the beginning of the setBirth() function: birth = new BirthInfo(); So the new setBirth() method looks as follows: public void setBirthInfo(int date, int month, int year, String place) { birth = new BirthInfo(); birth.setDate(date); birth.setMonth(month); birth.setYear(year); birth.setPlace(place); }