2015-07-21 78 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]; 
     ... 
    } 
相关问题