I keep getting a null pointer exception and I am not sure why. I looked at what causes this error but I still can't figure it out. I think after this error it may not be right but I can fix that after but first I have to fix this. This is the error I am getting:
----jGRASP exec: java PostOfficeTester
Exception in thread "main" java.lang.NullPointerException
at PostOffice.retrieveMsg(PostOffice.java:33)
at PostOffice.placeLetter(PostOffice.java:17)
at PostOfficeTester.main(PostOfficeTester.java:11)
----jGRASP wedge: exit code for process is 1.
----jGRASP: operation complete.
Here is code:
public class PostOfficeTester{
public static void main(String[] args)
{
PostOffice branch = new PostOffice(5);
branch.retrieveMsg(5);
branch.placeLetter(new Letter("Arnold", "I'll be back!"),5);
branch.placeLetter(new Letter("Spock", "Live long and prosper."),4);
branch.placeLetter(new Letter("Kirk", "KHAAAAAN!"),4);
branch.retrieveMsg(4);
branch.retrieveMsg(2);
branch.retrieveMsg(-1);
branch.placeLetter(new Letter("Harry", "Make my day!"),0);
branch.placeLetter(new Letter("Ellie", "Thanks for the adventure! Now go have another one!"), 1);
branch.placeLetter(new Letter("Buzz", "To infinity... and beyond!"), 3);
branch.findSender("Kirk");
branch.findSender("Ellie");
}
}
public class PostOffice {
private Letter pobox[];
public PostOffice(int size){
pobox = new Letter[size];
}
public boolean placeLetter(Letter mail, int boxNum){
if(boxNum>=pobox.length || (!(retrieveMsg(boxNum).equals("Empty!")))){
return false;
}
else{
return true;
}
}
public String retrieveMsg(int boxNum){
if(boxNum>=pobox.length){
return "Box does not exist!";
}
else if(pobox[boxNum].equals("")){
return "Empty!";
}
else{
return pobox[boxNum].getMsg();
}
}
public Letter findSender(String name){
for(int i = 0; i<pobox.length; i++){
if(name.equals(pobox[i].getSender())){
return pobox[i];
}
}
return null;
}
}
public class Letter {
private String sender;
private String message;
public Letter(String name, String text){
sender = name;
message = text;
}
public String getSender(){
return sender;
}
public String getMsg(){
return message;
}
}