Tezen Tezen - 9 months ago 46
Java Question

Java String index out of bounds with text file input

I am trying to split a

input into two using the following code:

public TypeValue(String line) {
while (line.charAt(i) != ' ') {
type = line.substring(0,i);
value = line.substring(i);

my input is a textfile that looks like this:

10 16
10 32
10 9024720
F 10
F 1
F 111111
F 100000
F 10110110100111001

However, I always get a
java.lang.StringIndexOutOfBoundsException: String index out of range: 13
. This only happens when I try to read the input from a text file. When I use the terminal to input the lines one by one it works just fine.

I have been looking for a couple hours but I cannot figure out what is causing this. It is also always "
", even when I delete all but the first line from the text file. Can anybody help me with this?


You should simply use line.split(" ") which will return an array of String, then get either the first or the second value using respectively the index 0 and 1 of the resulting array as next:

String[] values = line.split(" ");
type = values[0];
value = values[1];

Another way could be to use line.indexOf(' ') to get the index of the space character in your String.

int index = line.indexOf(' ');
// From 0 to the index where we found the space
type = line.substring(0, index);
// Starts from index + 1 to skip the space
value = line.substring(index + 1);