简体   繁体   中英

How to assign value of an array variable into another array variable

String[] msgoptions;
String[] finalmsgs3 = finalmsgs2[3].split("RR");
for(i = 1; i < finalmsgs3.length; i++)
{
    msgoptions[i] = finalmsgs3[i];
    Log.e(TAG, "---------------" + msgoptions[i]);
}

I need your help, if you can resolve issues of my code. Actually i'm trying to assign values of an array variable to another array variable. but i can't do that because got some errors. So, Could you any one help me..?

您需要在使用之前初始化数组msgoptions ,例如:

String[] msgoptions = new String[SIZE];

Rewrite your code to:

String[] finalmsgs3 = finalmsgs2[3].split("RR");     // switch first two lines
String[] msgoptions = new String[finalmsgs3.length]; // initilize the other array
for(i = 0; i < finalmsgs3.length; i++)               // Array index starts at 0
{
    msgoptions[i] = finalmsgs3[i];
    Log.e(TAG, "---------------" + msgoptions[i]);
}

A better solution would be:

String[] finalmsgs3 = finalmsgs2[3].split("RR");
String[] msgoptions = Arrays.copyOf(finalmsgs3, finalmsgs3.length);

Try that :

String[] msgoptions = = new String[SIZE];;
String[] finalmsgs3 = finalmsgs2[3].split("RR");
int j=0;
for(i = 0; i < finalmsgs3.length; i++)
{
    msgoptions[j] = finalmsgs3[i];
    j++;
    Log.e(TAG, "---------------" + msgoptions[i]);
}

First, on Java, you need to initialize your arrays. Also please note that they are based on 0 indexes.

So you should change your code to something like this:

String[] finalmsgs3 = finalmsgs2[3].split("RR");
String[] msgoptions = new String[finalmsgs3.length];
for(int i = 0; i < finalmsgs3.length; i++)
{
    msgoptions[i] = finalmsgs3[i];
    Log.e(TAG, "---------------" + msgoptions[i]);
}

But to do array copying you can avoid your code for using something more "standard" like java.util.Arrays.copyOf(T[] original, int newLength)

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