2013-11-04 25 views
1

我想寫一個基於我在我的side2 []數組中的對象的新文檔。 現在不幸的是,這個數組中的一些索引是空的,當它碰到其中的一個時,它只是給了我一個NullPointerException。這個數組有10個索引,但在這種情況下並不是所有的索引都需要。我試過try catch語句,希望在遇到null時繼續執行,但它仍然停止執行,並且不寫入新文檔。 作爲對象一部分的堆棧(srail)包含我想要打印的數據。避免我的數組中的空索引

這裏是我的代碼:

// Write to the file 
    for(int y=0; y<=side2.length; y++) 
    { 
     String g = side2[y].toString(); 

     if(side2[y]!=null){ 
      while(!side2[y].sRail.isEmpty()) 
      { 
       out.write(side2[y].sRail.pop().toString()); 
       out.newLine(); 
       out.newLine(); 
      } 
      out.write(g); 
     } 
    } 

    //Close the output stream/file 
    out.close(); 
} 
catch (Exception e) {System.err.println("Error: " + e.getMessage());} 

回答

3

的問題是,代碼檢查它null之前調用side2[y]對象toString()。您可以通過在循環頂部添加條件來跳過null對象,如下所示:

for(int y=0; y<=side2.length; y++) { 
    if(side2[y] == null) { 
     continue; 
    } 
    String g = side2[y].toString(); 
    // No further checks for null are necessary on side2[y] 
    while(!side2[y].sRail.isEmpty()) { 
     out.write(side2[y].sRail.pop().toString()); 
     out.newLine(); 
     out.newLine(); 
    } 
    out.write(g); 
} 
+0

好像我們今天在分享心靈。你得到這個 –