Getting ArrayIndexOutOfBoundsException Exceptions

痴心易碎 提交于 2019-12-01 15:31:16

This is because of line as you pointed out:

String name_dob = Child_DOB[i] + "  " + Child_DOB[i + 1];//this line

Say you have only one element in your Child_DOB array, you would enter your while loop, and with i = 0 try to access i+1 i.e. 1st element. Array starts with 0th index and hence accessing element at index 1 would throw ArrayIndexOutOfBoundsException. To avoid this one option would be:

while (i < Child_DOB.length - 1) {//go until second last element

This would work if your array has even number of elements. If you have odd number of elements then you would miss the last name (which should be fine as per your logic.)

if you really dont want to miss the last element, you could do something like:

if ((Child_DOB.length & 0X1) == 1) {
    Length_List.add(Child_DOB[Child_DOB.length - 1].length());
    //append to Children_Details_str.. better use StringBuilder here
}

Change your while loop condition as:

 while (i < Child_DOB.length - 1)

Explanation:

For example, Child_DOB.length is 5 and i value is 4, In your code:

    int i = 4;
    while (i < 5) {
        String name_dob = Child_DOB[4] + "  " + Child_DOB[4 + 1]; 

Here Child_DOB[5] causes ArrayIndexOutOfBoundsException because array index start from 0 and your Child_DOB index's are [0 1 2 3 4].

Hope this will help~

You have only one element in Child_DOB so Child_DOB.length=1, and inside while loop you are trying to access 2nd element Child_DOB[i + 1] in first iteration itself... So you are getting exception... Can you tell exactly what output you want??

Use-

while (i < Child_DOB.length - 1) 

Instead of -

while (i < Child_DOB.length)
Abdilahi

There is only one String in CHILD_DOB. In your while statement you typed Child_DOB[i + 1]; which accesses CHILD_DOB[1] but there is only one item in CHILD_DOB which is CHILD_DOB[0] Try this

String[] Child_DOB = new String[] {"KUSHAGRA",
 "(SON)-07/05/94AANVI", "(DAUGHTER)-12/06/00", "VARENYA", "(SON)", "-", "26/12/05"};

Which I think would fix your code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!