Reputation: 271
I am reading a csv file. One of the requirements is to check if a certain column has a value or not. In this case I want to check the value in array[18]
. However, I am getting
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 18
Is there any other way to check the array index if it has a value or empty?
My code:
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
}
}
}
Upvotes: 2
Views: 21135
Reputation: 2314
If its an arrayList then check if it contains null
array.contains(null));
Upvotes: -2
Reputation: 5325
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");
}
}
Upvotes: 0
Reputation: 5619
Look, according to JavaSE7:
ArrayIndexOutOfBoundsException thrown to indicate that an array has been accessed with an illegal index. (In your case) The index is greater than or equal to the size of the array.
Means, the index 18
is not legal for array record
in your code. Moreover if the array record
is null
then you will get another exception called NullPointerException
.
To overcome your problem, there are many solutions, one can be
//assuming that record is initialized
if(record.length > 18){
String readDateRecord = record[18];
...
}
Upvotes: 2
Reputation: 447
Size is fixed in array after creation .if you get index beyond of size then it's generated ArrayIndexOutOfBoundException
.So first you need to get the size of array then retrive the value from array
int size=record.length;
for(int i=0;i<size;i++)
{
if(record[i] != null){
// other processing here
}
}
Declare an array with size “n” and access the n-th element. However, as we already mentioned, the indices of an array with size “n”, reside in the interval [0, n – 1].
Upvotes: 0
Reputation: 11163
You may try the following code snippet -
int length = record.length;
if( (n>0 && n<length-1) && record[n] != null ){
String readDateRecord = record[n];
//other processing here
}
Upvotes: 0
Reputation: 13492
Here one approach is this
Object array[] = new Object[18];
boolean isempty = true;
for (int i=0; i<arr.length; i++) {
if (arr[i] != null) {
isempty = false;
break;
}
}
Upvotes: 0