In below code I am trying to do substring based on start and end index,But in end of the string.System is throwing ArrayIndexOutOfBoundsException. Please let me know, how to resolve this issue.
/**
* @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;
}
}
Regards,
chaitu
step by step debug your code:
first time variables
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 = 21andinitlenght = 40s.length()/initlength = 2start = 41andinitlength = 80.s.length()/initlength = 1andiequal to 2 therefore loop will break and program execution will finish.Based on your edit. Now it will loop for 5 times. And after 3rd time
start = 81andinitlength = 160which is out of range of string. For all the timetotal = 5.If you want that it will get the remaining part the try this:
output:-