-1

我得到一个空指针异常,但我不知道为什么。在将单元格读入字符串之前,我检查了该单元格是否为空。那么,为什么该字符串为空?

private void fillArray() 
{
    try 
    {
        readBook = new HSSFWorkbook(readFile);
    } 
    catch (IOException e) 
    {
        System.out.println("If we know what we're doing, no one should ever see this line.");
    }
    if (readBook != null) 
    {HSSFSheet infoSheet = readBook.getSheetAt(0);
        HSSFRow headingsRow = infoSheet.getRow(0);
        int i = 0;
        HSSFCell cell = headingsRow.getCell(i);
        String columnHeading = cell.toString();
        while (cell != null && !(cell.toString().equals(""))) 
        {
            cell = headingsRow.getCell(i);
            columnHeading = cell.toString();
            columnHeadings.add(columnHeading);
            i++;
        }
        if(columnListIsSetup == false)
        {
            createList();
            columnListIsSetup = true;
        }
    }
4

3 回答 3

5

我认为这是问题所在:

while (cell != null && !(cell.toString().equals(""))) 
{
    // We know that cell isn't null before this line...
    cell = headingsRow.getCell(i);

    // ... but now we've got a new value for cell, which could be null
    columnHeading = cell.toString();
    columnHeadings.add(columnHeading);
    i++;
}

我怀疑您想将其更改为:

while (cell != null && !(cell.toString().equals(""))) 
{
    // We know cell isn't null for this...
    columnHeading = cell.toString();
    columnHeadings.add(columnHeading);

    i++;
    // It's fine to set cell to null here... we'll be
    // checking again in a second...
    cell = headingsRow.getCell(i);
}
于 2012-07-06T21:30:15.847 回答
1
while (cell != null && !(cell.toString().equals("")))  {
    cell = headingsRow.getCell(i);      // here, cell gets reassigned so the 
                                        // "cell != null" check in the while 
                                        // loop condition loses it's value,
                                        // you need to check again

    if (cell == null)       // add the following to make sure the NEW cell value is not null
        break;              //

    columnHeading = cell.toString();
    columnHeadings.add(columnHeading);
    i++;
}
于 2012-07-06T23:20:06.630 回答
0

在确保单元格为空(或)为空之前,您正在做的事情String columnHeading = cell.toString();可能会在单元格为空的情况下导致 NullPointerException。

于 2012-07-06T21:11:43.820 回答