gpt4 book ai didi

java - 子字符串尝试处理错误(负)索引

转载 作者:行者123 更新时间:2023-12-02 06:37:19 26 4
gpt4 key购买 nike

我这里有一段代码给我带来了麻烦:

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

中间的线用于调试目的。但是,我得到的输出如下:

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)

为什么它说-240,而我需要的索引显然是253?

最佳答案

我假设 panoBuffer 包含多个逗号,这可能会导致您在 idIndex 之前找到一个逗号。

尝试更换panoBuffer.indexOf(',') 改为 panoBuffer.indexOf(',', idIndex+1) ,这样您将找到第一个逗号 idIndex 之后。

您还应该确保通过验证 indexOf 的结果是否大于 String#indexOf(int,int) 文档中指定的 -1 来检查您是否确实找到了一个值.

关于java - 子字符串尝试处理错误(负)索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19502099/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com