0

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.

Puki
  • 157
  • 1
  • 2
  • 8
  • 2
    Note that you do `',' + 1` i.e. you add one onto a comma. This results in the character after comma in the character table. So you do not search for comma, but for the other character. – Zabuzard Nov 25 '18 at 21:28
  • 2
    Don't guess and assume, just check it. Print the result and see what it actually is. `System.out.println(t1.lastIndexOf(','+1);`. (Or learn to use a debugger) – Zabuzard Nov 25 '18 at 21:28
  • 1
    @Aomine yes that was the problem, +1 was in the brackets, thank you! – Puki Nov 25 '18 at 21:32

0 Answers0