2012-07-06 177 views
-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; 
     } 
    } 
+7

有很多地方是*可能*扔NullPointerException異常 - 什麼堆棧跟蹤說? – 2012-07-06 21:10:37

+0

它追溯到行columnHeading = cell.toString(); – user1507835 2012-07-06 21:18:09

+2

然後顯示'cell'爲空......或者它在'toString'內被拋出。 – 2012-07-06 21:19:01

回答

0

之前確保電池爲空(或)空,你正在做的String columnHeading = cell.toString();可能的情況下,將導致空指針異常,其中電池是空的。

+0

謝謝,我試過了,但仍然得到例外。它很奇怪,因爲我是隨機做的,現在每次運行它,我都會得到這個異常,而且沒有任何改變。 – user1507835 2012-07-06 21:15:44

+0

...因爲它*是隨機做的... – user1507835 2012-07-06 21:16:26

+3

更新Stacktrace的問題。 – kosa 2012-07-06 21:16:52

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