Вопрос

I have a snippet of code here that is giving me trouble:

    idIndex = panoBuffer.indexOf("\"photo_id\":");
    System.out.println(idIndex);
    photos[i].id = panoBuffer.substring(idIndex, panoBuffer.indexOf(','));

The middle line is for debug purposes. However, the output I get is as follows:

253
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -240
at java.lang.String.substring(Unknown Source)
at panoramio.Panoramio.jsonToArray(Panoramio.java:248)
at panoramio.Panoramio.main(Panoramio.java:83)

Why does it say -240 when clearly the index of what I require is 253?

Это было полезно?

Решение

I assume that panoBuffer contains more than one comma, which perhaps leads to that you find a comma that comes before idIndex.

Try replacing panoBuffer.indexOf(',') with panoBuffer.indexOf(',', idIndex+1) instead, this way you will find the first comma that comes after idIndex.

You should also make sure to check that you actually do find a value by verifying that the result of indexOf is greater than -1 as specified in the documentation for String#indexOf(int,int).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top