I have a method that parses line of text, such as 24/11/2018, Drive, -2.00,
and returns the number before the last comma, this case being -2
. Here is the method:
public static int value (String line){
//-5 becasue of characters after dot, t1 becomes "24/11/2018, Drive, -2"
String t1= red.substring(0, red.length()-5);
String t2=t1.substring(t1.lastIndexOf(','+1));
return Integer.parseInt(t2);
}
This method has no problem working with negative values such as the case above, but when the value is positive like this line 15/11/2018, Tata, 50.00,
I get the StringIndexOutOfBoundsException:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -1
at java.lang.String.substring(String.java:1927)
at ParseCSV.vrijednost(ParseCSV.java:30)
at Main.main(Main.java:30)
Which points at the line String t2=t1.substring(t1.lastIndexOf(','+1));
, and at the String class at throw new StringIndexOutOfBoundsException(beginIndex);
. I suppose this means that my begin index t1.lastIndexOf(','+1)
is nowhere to be found, meaning that there is no ,
character even though it clearly is there. This problem appears only for positive values and I have no idea why.