在下面的代码中,我尝试根据开始和结束索引执行子字符串,但在字符串末尾。系统抛出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;
}
}
问候,
柴图
最佳答案
逐步调试您的代码:
首次变量
开始=0; 初始长度=0; s="有些人将接受与冷漠混为一谈,但世界上是有区别的"; 总计 = 5。
s.length()/initlength = 4.
- 第一个子字符串为 0 到 20。
start = 21
和initlenght = 40
- 第二次循环
s.length()/initlength = 2
- 从 21 到 40 的子字符串。
start = 41
和initlength = 80
。- 第三次循环。
s.length()/initlength = 1
且i
等于 2,因此循环将中断,程序执行将完成。
基于您的编辑。现在它将循环 5 次。第三次 start = 81
和 initlength = 160
超出了字符串范围。始终总计 = 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
关于java - 带循环的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5991494/