Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

I have a question, but I don't know how can I do?

 
Feng Guo
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Greeting everybody:
I have a duzzle,just then these code, but I don't know why it will throw NullPointerException. Please help me. Thanks all.
...
FileHeader header = new FileHeader(magic,headerLen,fieldCount);
for (int i = 0; i < fieldCount ; i++ )
{
short fieldLen = db.readShort();
header.fieldInfo[i].setFieldLen(fieldLen); //<------ throw :java.lang.NullPointerException
byteArray = new byte[fieldLen];
db.readFully(byteArray);
header.fieldInfo[i].setFieldName(new String(byteArray));
header.fieldInfo[i].setFieldSize(db.readShort());
}

...


class FileHeader
{
int magic;
int headerLen;
short fieldCount;
FieldInfo[] fieldInfo;

public FileHeader(int magic, int headerLen, short fieldCount)
{
this.magic = magic;
this.headerLen = headerLen;
this.fieldCount = fieldCount;
fieldInfo = new FieldInfo[fieldCount];
}
};

public class FieldInfo
{
private short fieldLen;
private String fieldName;
private short fieldSize;

public void setFieldLen(short fieldLen)
{
this.fieldLen = fieldLen;
}

public void setFieldName(String fieldName)
{
this.fieldName = fieldName;
}

public void setFieldSize(short fieldSize)
{
this.fieldSize = fieldSize;
}

public short getFieldLen()
{
return fieldLen;
}

public String getFieldName()
{
return fieldName;
}

public short getFieldSize()
{
return fieldSize;
}
};
 
Joyce Lee
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Feng Guo,



Hope that helps.

Joyce
[ October 04, 2004: Message edited by: Joyce Lee ]
 
Mike Vess
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"header.fieldInfo[i].setFieldLen(fieldLen); //<------ throw :java.lang.NullPointerException"

This is ugly! The Fields in FileHeader class should be private and NOT package protected. The reson that you get a Null Pointer is that the references in fieldInfo Array are null. When you do "new FieldInfo[fieldCount]" you only create the Array, not the Objects in it.
 
Feng Guo
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your help,Joyce.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic