Java。lang.StringIndexOutOfBoundsException:字符串索引超出范围:11
我被这件事缠住了,找不到解决办法。获取线程“main”java中的异常错误。lang.StringIndexOutOfBoundsException:字符串索引超出范围:11
有人能帮忙解决这个问题吗? 我的代码:
public static void main(String[] args) {
try {
Scanner sc = new Scanner(new File("Testing.txt"));
int i = 0;
while(sc.hasNext()){
String line = sc.nextLine();
char needle = line.charAt(i);
while(i < line.length()){
if(Character.isUpperCase(needle)) {
while(needle != ' '){
System.out.print(needle);
i++;
needle = line.charAt(i);
}
System.out.println(needle);
}
else{
i++;
needle = line.charAt(i);
}
}
}
}
catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}
# 1 楼答案
根据我上面的评论,使用String
split
方法是很容易的。当然input
可以替换为文件中的文本,使用expectedResult
和测试输出是否等于完全是可选的输出
# 2 楼答案
我的假设是你的错误就在这里
及
在增加索引时,不检查索引是否存在
# 3 楼答案
我不确定你想要实现什么。但是从您的错误中,我可以说您正在尝试递增索引计数器,然后尝试访问字符串中的元素
在
while
循环和else
块中,有以下语句:将两者都更改为:
您的代码将在没有上述异常的情况下运行
我做了上面提到的更改,并做了一些更改
int i=0;
的声明。文本文件中不止一行需要这样做李>char needle = line.charAt(i);
语句,因为需要为每一行初始化指针李>它打印以下输出:
希望这有帮助