gpt4 book ai didi

java - 使用子字符串会产生 StringIndexOutOfBoundsException : String index out of range: -1 exception

转载 作者:太空宇宙 更新时间:2023-11-04 13:38:28 25 4
gpt4 key购买 nike

搜索时,标签处的字符串为abc:xyz

但这给出了

`StringIndexOutOfBoundsException`: String index out of range: -1 exception. 

在行:

tag = strLine.substring(0, strLine.indexOf(':'));

可能的错误是什么?

提前致谢!

最佳答案

strLine.substring(0, strLine.indexOf(':')); 

上面的代码将尝试从 0(含)到某个正 int 值。但 strLine.indexOf(':') 返回 -1,因为 : 不在 strLine 中。所以最后这个方法变成了 subString(0, -1),这给了你错误:-

StringIndexOutOfBoundsException:字符串索引超出范围:-1 异常。

做这样的事情可以防止:-

int i = strLine.indexOf(':')
if(i != -1)
tag = strLine.substring(0, i);
else {//handle error here}

或者

try{
tag = strLine.substring(0, strLine.indexOf(':'));
}
catch(StringIndexOutOfBoundsException ex){
// catch here
}

PS:- StringIndexOutOfBoundsException 是一个运行时异常,不应该被捕获,而应该被处理/修复。

关于java - 使用子字符串会产生 StringIndexOutOfBoundsException : String index out of range: -1 exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31453560/

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