简体   繁体   中英

Error java.lang.ArrayIndexOutOfBoundsException:

I pass string value to this method.but im getting Array index bound exception please help me.

public void separateCards(String cards)
{
    cardNames+=cards+"-";
    String[] parts = cardNames.split("-");
    String part1 = parts[0]; // 004
    String part2 = parts[1]; // 034556
    Toast.makeText(getActivity(), part1,Toast.LENGTH_SHORT).show();
}
}

My logcat

  03-28 11:27:41.213: E/AndroidRuntime(22392): FATAL EXCEPTION: main
    03-28 11:27:41.213: E/AndroidRuntime(22392): java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
    03-28 11:27:41.213: E/AndroidRuntime(22392):    at com.compareCr.ListvCompare.separateCards(ListvCompare.java:760)
    03-28 11:27:41.213: E/AndroidRuntime(22392):    at com.compareCr.ListvCompare$2$1.onClick(ListvCompare.java:627)
    03-28 11:27:41.213: E/AndroidRuntime(22392):    at android.view.View.performClick(View.java:4261)
    03-28 11:27:41.213: E/AndroidRuntime(22392):    at android.view.View$PerformClick.run(View.java:17356)
    03-28 11:27:41.213: E/AndroidRuntime(22392):    at android.os.Handler.handleCallback(Handler.java:615)
    03-28 11:27:41.213: E/AndroidRuntime(22392):    at android.os.Handler.dispatchMessage(Handler.java:92)

you append "-" at the end of the string and therefore when you split , you get only one value.

therefore this String part2 = parts[1]; throw array index out of bound exception.

you need to put "-" in between string.

You add the - in the wrong place. Giving you the value as(I assume the initial value of cardNames is 004 )

"004034556-"

You should do:

cardNames += "-" +cards;

Which will give you:

"004-34556"

But seriously what is the purpose of combining the String and split it again at the same way?

Wouldn't it be easy if you just do like this?

String part1 = cardNames; 
String part2 = cards;

Note: You should always check that the index element that you want to access must less that parts.length

I think there is only single " - " in your cardNames value, that's why you getting error..

So better to use For loop for getting all data from Array

    String[] parts = cardNames.split("-");
    for (int i = 0; i < parts.length; i++) {
        String partsData = parts[i]; 
    }

Updated:

cardNames=cardNames+"-"+cards;

String parts1;
String parts2;
String[] parts = cardNames.split("-");
for (int i = 0; i < parts.length; i++) {
    if(i==0)
        parts1= parts[i];
    else if(i==1)
        parts2= parts[i];
}

当没有“-”的东西传递给您的方法时,例如“ foo”,当您调用“ foo-”。split()时,它变成“ foo-”,它返回[“ foo”],因此,如果您尝试访问索引1,它将越界。

Have you print "cards"?

I think cardNames is "somethig-"; then parts = {'something'}

so, parts[1] is out of index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM