[Solved] String index out of range: -5 [closed]


You have misunderstood what argument Java’s String.substring function takes.

In short, you appear to think the argument takes the length of the substring. It doesn’t – rather, it specifies the “begin-index” – ie. where in the supplied string to start copying.

So when you say :

final String year = "yyyy ";
args[0] = year.substring(5);

you are NOT actually setting args[0] to a 5-character string. In stead, you are setting it to the part of string “yyyy ” starting at position 5 – in other words, you are setting it to empty-string.

So when you subsequently say

final Integer yyyy=Integer.valueOf(args[ZERO].substring(FIVE)),

and assuming you have ZERO set to 0 and FIVE to 5, this will fail since you have args[0] as empty-string “”, and you can’t get a substring starting at position 5 from “”.

To sum up, if you have

    String myString = "smiles";

    System.out.println("substring(0, 4) = <" + myString.substring(0, 4) + ">");
    System.out.println("substring(2, 4) = <" + myString.substring(2, 4) + ">");
    System.out.println("substring(4)    = <" + myString.substring(4) + ">");

the output will be :

substring(0, 4) = <smil>
substring(2, 4) = <il>
substring(4)    = <es>

In short, get rid of your “.substring” calls in both your test and your main code.

Check out the spec at https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int)

1

solved String index out of range: -5 [closed]