indexoutofboundsexception Java未按预期获得“StringIndexOutOfBoundsException”
我有以下代码
public class test{
public static void main(String[] args){
String one = "x";
if(one.charAt(one.indexOf('x')+1)== 'p'){
System.out.println("test");
}
}
}
这会导致以下错误:
线程“main”java中出现异常。lang.StringIndexOutOfBoundsException:字符串索引超出范围:1 在爪哇。朗,弦。charAt(String.java:658) 在测试中。main(test.java:4)
我预计会发生这种情况,我的理解是,这是因为字符串只有1个索引(0),所以不可能在索引1处找到字符
one.charAt(one.indexOf('x')+1)== 'p'
如果我的理解是正确的,我无法理解为什么其他程序没有同样的问题
class XClass{
boolean doubleX(String str){
boolean is = false;
int indexes = str.length()-1;
if(str.indexOf('x')== indexes){
is = false;
}else if(str.charAt(str.indexOf('x')+1)=='x'){//same code as the program above
is = true;
}
return is;
}
}
public class ImplementXClass{
public static void main(String[] args){
XClass Xmen = new XClass();
boolean result = Xmen.doubleX("x");
System.out.println(result);
}
}
即使方法参数是带有一个索引(“x”)的字符串,该程序也能成功编译
- 如果没有索引1,程序如何运行这一行str.charAt(str.indexOf('x')+1)='x'李>
- 它不应该作为第一个程序编译失败吗李>
- 我错过了什么李>
# 1 楼答案
# 2 楼答案
由于
str
是"x"
,所以else if
甚至没有运行if
条件是}
true
,因为str.indexOf('x')
返回0
,而indexes
也是0
{因此,
is
被设置为false
,并且else if
条件永远不会被计算。因此,没有IndexOutOfBoundsException
发生# 3 楼答案
因为您的一个字符串通过了第一个
if
条件你的
else if
没有被评估