我一直得到一个空指针异常,我不知道为什么。我查看了导致此错误的原因,但我仍然无法弄明白。我认为在这个错误之后它可能不对,但我可以解决这个问题,但首先我必须解决这个问题。这是我得到的错误:
----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.
这是代码:
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;
}
}
公共班级信件{
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;
}
}