本文介绍了空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到空指针异常,但我不知道为什么.在将其读取为字符串之前,我检查了该单元格是否为空.那么,为什么该字符串为空?

I am getting a null pointer exception, but I dont know why. I checked to see if the cell was null before I read it to a string. So, why is that string null?

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;
        }
    }

推荐答案

我认为这是问题所在:

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);
}

这篇关于空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-13 17:41