2014-02-27 71 views
0

打印時我有此以下代碼:異常從數組

public void Print() { 
     String formatString = "%12s %7s %9s\n"; 
     System.out.format(formatString, "Surname", "Initial", "Extension"); 
     for (int i = 0; i < directory.length - 1; i++) { 
      System.out.format(formatString, (Object[]) directory[i].split("\t")); 
     } 

    } 

此代碼的點是使其中包含有類似「史密斯我0472」(空間實際上是一個標籤)的陣列。如果數組的大小是要打印的數據量,則此代碼完美工作,但如果數組例如爲100,並且我只有20個元素,則會引發錯誤。我需要這個數組是這個大小。謝謝。

對不起,如果我沒有足夠清楚。

回答

4

打印前不能檢查元素是否爲null

for (int i = 0; i < directory.length - 1; i++) { 
    if (directory[i] != null) { 
     System.out.format(formatString, (Object[]) directory[i].split("\t")); 
    } 
}