Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

java - Null Pointer Exception

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;
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think this is the problem:

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

I suspect you want to change it to:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...