tags:

views:

149

answers:

5

I'm stuck with this pretty silly thing;

I got a textfile like this;

Hello::140.0::Bye

I split it into a string array using;

LS = line.split("::");

Then I try to convert the array values containing the number to a double, like this;

Double number = Double.parseDouble(LS[1]);

But I get the following error message;

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

Does anyone have any idea why this doesn't work?

+2  A: 

That error has nothing to do with that line of code. Look for somewhere where you're trying to access index 3 of an array. LS in this example should only have indexes 0-2.

Paul Tomblin
Oops, my bad, I generalized my own code, the exception now refers to the correct index.
cc0
+4  A: 

I think it's a problem with reading the file. Did you try printing line and also the contents of LS after splitting?

Halo
Yes, the line prints fine with the correct value, even after that parseDouble conversion.
cc0
Ahhh, I just had an empty line in the textfile, DOH! Thanks for the help!
cc0
A: 

what type is LS?? This code works for me:

public class Test
{

    public static void main(String[] args)
    {
        String s = "Hello::140.0::Bye";
        String[] ls;
        ls = s.split("::");
        System.out.println(ls[1]);
        double d = Double.parseDouble(ls[1]);
        System.out.println(d);
    }
}
Daniel Persson
+1  A: 

I think some lines don't contain data in the specified format. Does the file contains empty lines? In this case the split returns only a single-element array. To find the problem, you could print the line (of the data), on which the error occurs.

Mnementh
A: 

You should a compiler, such as Eclipse, which allows you to debug the code dynamically. The issue here is that the Array LS has a size <=1. This could be caused by incorrectly reading the text file as Halo mentioned or as Mnementh mentioned by having a blank line. This will infact occur for any line that does not contain the :: delimiter.

You should perform a check to ensure that the Array LS contains >X entries, especially if you are reading in from a file where entries could vary.

double number = 0.0
if( LS.size() > 3 ){
    number = Double.parseDouble(LS[1]);
}
Alphie