【发布时间】:2014-09-12 22:07:18
【问题描述】:
我有以下代码
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 在 java.lang.String.charAt(String.java:658) 在 test.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' 这一行。
- 不应该作为第一个程序编译失败吗?
- 我错过了什么?
【问题讨论】:
-
因为该代码永远不会被执行。并且第一个程序没有编译错误。
标签: java indexoutofboundsexception