Brick Brick - 1 month ago 12
Java Question

Why split() method is not working

I have this code but it throws this exception

java.lang.ArrayIndexOutOfBoundsException: 1.


have any idea why the split() doesn' t work properly??
(i know that this line has two integers to be readen)

line = br.readLine();
String dimensions[]= line.split("\\s*[a-zA-Z]+\\s*");
String i = dimensions[0];
String j = dimensions[1];


The input is a file with integers separated with
" "
.

Answer

The java regex you're looking for is \\s+

It works. Your problem is, that the input doesn't get split so the returned array is length 1. It means that the highest index you can access is 0.

We know it because of the StackTrace which is full of information even in so shortened form. It says, that the index on which the Exception is thrown is 1 and we know that it's IndexOutOfBoundsException.

You write that the input is a file with integers separated with " ". Your line isn't splited because your regex expects at least one [a-zA-Z] character.