簡體   English   中英

為什么這會引發NullPointerException?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM