2015-07-21 34 views
2

我正在閱讀一個csv文件。其中一個要求是檢查某個列是否有值。在這種情況下,我想檢查array[18]中的值。但是,我越來越如何檢查數組[]在java中有一個空值?

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 18 

是否有任何其他方式來檢查數組索引,如果它有一個值或空?

我的代碼:

while ((sCurrentLine = br.readLine())!= null) { 

    String[] record = sCurrentLine.split(","); 

    if(record.length > 0){ // checking if the current line is not empty on the file 
     if(record[18] != null){ // as per console, I am getting the error in this line 
      String readDateRecord = record[18]; 
      // other processing here 
     } 
    } 
} 
+1

得到數組的長度第一,你能避免IndexOutfBoundsException.Or別人趕上ArrayOutofBoundsException – Renjith

+1

例外說,有在不元素這個陣列中的位置。向我們展示將元素添加到數組的代碼。 – Kiki

+0

'record!= null' –

回答

0

這一個辦法是這樣的

Object array[] = new Object[18]; 
boolean isempty = true; 
for (int i=0; i<arr.length; i++) { 
    if (arr[i] != null) { 
    isempty = false; 
    break; 
    } 
} 
0

你可以試試下面的代碼片段 - 後

int length = record.length; 
if((n>0 && n<length-1) && record[n] != null){ 

    String readDateRecord = record[n]; 
    //other processing here 

} 
0
public static void main (String[] args) { 
    Integer [] record = {1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1}; 
    for(int i = 0; i < record.length; i++) 
     if(record[i] == null) { 
      System.out.println(i+1 + " position is null"); 
     } 
} 
+0

這將簡單地打印出「null null」,這看起來很愚蠢。最好將索引'i'加到println – Ian2thedv

+0

是的,你是正確的 – xrcwrn

0

大小是固定的陣創造。如果你的索引超出了規模ñ它產生ArrayIndexOutOfBoundException。所以首先你需要得到數組的大小,然後從數組

int size=record.length; 
for(int i=0;i<size;i++) 
    { 
    if(record[i] != null){ 
    // other processing here 
    } 
} 

retrive值聲明大小爲「N」陣列並進入第n個元素。但是,正如我們已經提到的,大小爲「n」的數組的索引駐留在區間[0,n-1]中。

2

看,根據JavaSE7

ArrayIndexOutOfBoundsException異常拋出,指示數組已經 一直與非法索引訪問。 (就你而言)索引是 大於或等於數組的大小。

意思是,索引18在您的代碼中對於數組record不合法。此外,如果數組recordnull那麼您將得到另一個異常,稱爲NullPointerException

爲了解決你的問題,解決方法有很多,可以是

//assuming that record is initialized 
if(record.length > 18){ 
     String readDateRecord = record[18]; 
     ... 
    } 
相關問題