字符串越界问题。。

呆到深处自然萌2 2011-08-16 10:20:53
import java.util.ArrayList;
import java.util.List;

public class Split4 {
public static void main(String args[]) {
String Str = "aa-bb-cc-dd";
int i = 0;
List<String> l = new ArrayList<String>();
try {
while (Str.indexOf("-") > -1) {
l.add(Str.substring(i, Str.indexOf("-",i)));
i = Str.indexOf("-",i) + 1;//
}
} catch (RuntimeException e) {
e.printStackTrace();
}
System.out.println(l);

}
}


java.lang.StringIndexOutOfBoundsException: String index out of range: -10
at java.lang.String.substring(String.java:1938)
at mianshiti.Split4.main(Split4.java:13)[aa, bb, cc]

那个给分析下异常?
...全文
187 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
lflljt 2011-08-18
  • 打赏
  • 举报
回复
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 cbxjj 的回复:]
while (Str.indexOf("-",i) > -1) {
加上红色部分
[/Quote]哈哈 这么快就到家啊
恩 刚才调晕啦 谢谢啊
剑神一笑 2011-08-16
  • 打赏
  • 举报
回复
while (Str.indexOf("-",i) > -1) {
加上红色部分
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 javaxiaochouyu 的回复:]
当i= 9后 条while里面的条件还为真 那么就会进入while继续执行 以至抛出越界异常...
[/Quote]en xiexie haha
Jeelon 2011-08-16
  • 打赏
  • 举报
回复
当i= 9后 条while里面的条件还为真 那么就会进入while继续执行 以至抛出越界异常...
Jeelon 2011-08-16
  • 打赏
  • 举报
回复
第三次分割的时候 i= 9了 开始执行这句
l.add(Str.substring(i, Str.indexOf("-",i)));
此时可写成l.add(Str.substring(9, Str.indexOf("-",9)));
Str.indexOf("-",9)找不到 返回-1
l.add(Str.substring(9,-1);则截取的字符串长度为 -1-9 = -10;
shuwei003 2011-08-16
  • 打赏
  • 举报
回复
2楼正解
softroad 2011-08-16
  • 打赏
  • 举报
回复
检查下i的值
wd9053 2011-08-16
  • 打赏
  • 举报
回复
import java.util.ArrayList;
import java.util.List;

public class Split4 {
public static void main(String args[]) {
String Str = "aa-bb-cc-dd";
int i = 0;
List<String> l = new ArrayList<String>();
try {
while (Str.indexOf("-", i) > -1) {
l.add(Str.substring(i, Str.indexOf("-",i)));
i = Str.indexOf("-",i) + 1;//
}
} catch (RuntimeException e) {
e.printStackTrace();
}
System.out.println(l);

}
}

while语句一直为true
softroad 2011-08-16
  • 打赏
  • 举报
回复
我靠,又发一个帖子,分真多。
看Split4.java:13

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧