在下面的代码中,我试图根据开始和结束索引来做子串,但是在字符串的末尾。系统正在抛出ArrayIndexOutOfBoundsException
。请告诉我,如何解决此问题。
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int initlength = 20;
int start = 0;
String s = "Some people confuse acceptance with apathy, but there's all "+
"the difference in the world";
int total=(int)Math.ceil((double)s.length()/(double)initlength);
for (int i = 0; i < total; i++) {
System.out.println("s length" + s.substring(start, initlength));
start = initlength + 1;
initlength = initlength + initlength;
}
}
此致
chaitu
答案 0 :(得分:1)
逐步调试代码:
第一次变量
start=0;
initlength=0;
s="Some people confuse acceptance with apathy, but there's all the difference in the world";
total = 5.
s.length()/initlength = 4.
start = 21
和initlenght = 40
s.length()/initlength = 2
start = 41
和initlength = 80
。s.length()/initlength = 1
和i
等于2因此循环将中断,程序执行将完成。根据您的修改。现在它将循环5次。在第3次start = 81
和initlength = 160
超出字符串范围之后。始终total = 5
。
如果你想要它将获得剩下的部分,试试这个:
int initlength = 20;
int start = 0;
String s = "Some people confuse acceptance with apathy, but there's all "
+ "the difference in the world";
int total = (int) Math.ceil((double) s.length() / (double) initlength);
for (int i = 0; i < total; i++) {
if(initlength<s.length()){
System.out.println("s length" + s.substring(start, initlength));
start = initlength + 1;
initlength = initlength + initlength;
} else {
initlength = s.length();
System.out.println("s length" + s.substring(start, initlength));
break;
}
}
输出: -
s lengthSome people confuse
s lengthcceptance with apat
s lengthy, but there's all the difference in th
s length world
答案 1 :(得分:0)
initlength
是不是会越来越大,直到超过字符串的末尾?