[英]Why is this throwing a NullPointerException?
我想弄清楚为什么在此代码中出现NullPointerException
。
以下是相关的代码段。
(主要)
...
try (RawData setupData = new RawData(
new File(fileName), log);) {
while (true) {
record = setupData.nextRecord();
if (record == null)
break;
System.out.println(record.getCountryCode());
System.out.println(record.getCountryID());
table.put(record);
index.put(record);
count++;
}
} catch (IOException e) {
e.printStackTrace();
}
...
(投入方法)
public void put(DataTableRecord country) {
this.current = country;
try {
this.file.seek(this.current.getCountryID() * RECORD_SIZE);
if (!exists(this.current.getCountryID())) {
writeExternal(this.current);
this.size++;
if (country.getCountryID() > this.last)
this.last = country.getCountryID();
}
} catch (IOException e) {
e.printStackTrace();
}
}
(writeExternal方法)
private void writeExternal(DataTableRecord data) throws IOException {
System.out.println(data.getCountryCode());
this.file.writeUTF(data.getCountryCode());
this.file.writeShort(data.getCountryID());
this.file.writeUTF(data.getName());
switch (data.getContinent()) {
case AFRICA :
this.file.writeShort(1);
break;
...
case SOUTH_AMERICA :
this.file.writeShort(7);
break;
}
this.file.writeInt(data.getArea());
this.file.writeLong(data.getPopulation());
this.file.writeFloat(data.getLifeExpectancy());
}
每次循环都成功执行两次,并且在第三次迭代中,我得到了NullPointerException
。 已插入System.out.writeln
调用以进行调试。 从writeln
调用中,我可以看到传递给writeExternal
方法的对象在调用该方法之前不为null。 在第三次迭代中,出现以下错误:
Exception in thread "main" java.lang.NullPointerException
at edu.wmich.cs3310.jwhite_cotw.DataTable.writeExternal(DataTable.java:255)
at edu.wmich.cs3310.jwhite_cotw.DataTable.put(DataTable.java:159)
at edu.wmich.cs3310.jwhite_cotw.Setup.main(Setup.java:62)
我不知道null
的来源。 对象如何能为空时,它不是null
立即调用这个方法之前? 有人有什么想法吗? 我应该提到字段“ this.file”是一个用“ rw”打开的RandomAccessFile
。
DataTable.java:255是这一行
this.file.writeUTF(data.getCountryCode());
DataTable.java:159是这一行
writeExternal(this.current);
和Setup.java:62是行
table.put(record);
任何建议(甚至只是正确方向的一点)都将受到赞赏。
错误是当writeExternal
参数为null
。 所以这个陈述是有问题的
writeExternal(this.current);
如果您将其更改为
writeExternal(country);
它可以使您免于出错,但是您可能应该重新设计代码以处理nullpointer异常,或者至少使用throws子句对其进行声明。
因为我很通灵,所以我可以说出问题所在...
countryCode字段的类型为Integer
,但exist exists()
的参数类型为int
。 这意味着当将countryCode传递给该方法时,Integer将自动拆箱为int,但是如果countryCode为null,则此操作将导致NPE。
将参数的类型更改为Integer,并确保该方法处理传递的null。
免责声明:字段和方法名称可能不正确,但是我很确定一般原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.