USB
USB

Reputation: 6139

java.lang.Exception: java.lang.ArrayIndexOutOfBoundsException: 7

I am trying to store each line of a file into a String array.

/*
*Input file
*2 1 1 1 1 1 1.33 1
*4 2 15 3 9 3 0.185
*/

String[][] data_array = new String[1][7];
int i = 0;
int j = 0;
//file read
StringTokenizer tokenizer =new StringTokenizer(line,delim);
while (tokenizer.hasMoreTokens()) {
    String token = tokenizer.nextToken();
    data_array[i][j] = token;
    j++;
}

But showing

java.lang.Exception: java.lang.ArrayIndexOutOfBoundsException: 7

But When I am trying with

String[][] data_array = new String[1][8];

I am not getting this exception instead I am getting below as the output.

2 1 1 1 1 1 1.33 1 null
4 2 15 3 9 3 0.185 null

Upvotes: 0

Views: 1445

Answers (3)

RayanFar
RayanFar

Reputation: 587

you must use array in your method not in the body of your class!

and arrays first element have index=> 0 and the lastest element have index=> N-1

Upvotes: 0

Aleks G
Aleks G

Reputation: 57316

In java, arrays are 0-based, that is the first element will have index 0 and the last element will have index n - 1 (where n is the length of the array).

As your array is declared [1][7], the last index will be number 6. Your first row contains 8 values, therefore you end up trying to load the 8th value (index 7) into an array containing 7 elements. Using index 7 results in an IndexOutOfBoundException.

Moreover, in your particular case, the first row of the input contains 8 elements, but the second row only contains 7 elements. If you try to load 7 values into the array containing 8 elements, the last one will be null. For the input you specified, with array declared as having length 8, the output would be:

2   1   1   1   1   1   1.33    1
4   2   15  3   9   3   0.185   null

(Note that I added extra spaces to indicate better how the array is populated.)

Further, it makes little sense to declare a two-dimensional array with the first dimension being 1 - it's the same as declaring a single-dimension array. What you probably want to do is have an array with first dimension referring to rows in the file and second dimension referring to values in rows.

Upvotes: 1

Steven Pessall
Steven Pessall

Reputation: 993

The elements of an array with length i are numbered 0 to i-1.

I assume you are using blanks as delimeters. Is there a trailing blank at the end of the line? This would explain why you are getting one surplus token.

Upvotes: 0

Related Questions