d2jsp
Log InRegister
d2jsp Forums > Off-Topic > General Chat > Homework Help > Help Reading From File > Java
Add Reply New Topic New Poll
Member
Posts: 5,299
Joined: Jul 4 2009
Gold: 2,632.57
Jan 20 2015 12:17pm
When I compile my program, I'm getting an array out of bounds exception, and I think it has to do with the way I'm reading in lines from a txt file.

The error pops up because of the line that accesses elements[1]:

Scanner in = new Scanner(inFile);
while(in.hasNextLine()){
String line = in.nextLine();
String [] elements = line.split("\\s+");
name.add(elements[0]);time.add(Integer.parseInt(elements[1]));
value.add(Integer.parseInt(elements[2]));
}

I think when I'm creating the array, it's not splitting the line correctly. It may have something to do with the regex, //s+, I tried some other notations for the regex including just /s, and a few others I found online, but I'm always getting the error.

The text file is formatted with a string (space) int (space) int:
name 1 2
name 2 3
...

I'd greatly appreciate any help!

This post was edited by furbyjs on Jan 20 2015 12:18pm
Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Jan 20 2015 02:24pm
Instead of telling you the answer, i'm gonna tell you how to trouble shoot this on your own.

String line = in.nextLine();
//log this line so you can see what's inside

String [] elements = line.split("\\s+");
// log this array so you can see how it got split with your regex

also, i prefer using apache's stringutils for this.
Go Back To Homework Help Topic List
Add Reply New Topic New Poll