Java中的NullPointerException错误
我正在制作一个包含对象的类。retrieveMessage方法有问题,因为当我测试它时,它返回一个NullPointerExceptionJava中的NullPointerException错误,java,nullpointerexception,Java,Nullpointerexception,我正在制作一个包含对象的类。retrieveMessage方法有问题,因为当我测试它时,它返回一个NullPointerException public class PostOffice { public PostOffice(int size) { boxbox = new Letter[size]; } public boolean placeLetter(Letter mail, int boxNum)
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];
}
}
公营邮政局
{
公共邮政局(内部大小)
{
boxbox=新字母[大小];
}
公开信(信件邮件,int-boxNum)
{
如果(((boxNum>(boxbox.length-1))| |(boxNum我猜这一行会抛出NullPointerException:
String swag = boxbox[boxNum].getMsg();
创建时,boxbox
具有大小值,所有值均为空
您应该首先检查是否boxbox[boxNum]
是否为空。如果为空,则意味着邮箱中不包含字母。请发布堆栈跟踪。什么为空?堆栈跟踪在哪里?告诉我们它出现在哪一行?NullPointerException可能是所有Java异常中最容易调试的。了解如何调试。从实际阅读您创建的异常信息开始等类型更改if(框号)不可能重复