I am trying to append two arrays together, so that the method will take in the current array, and then afterwards take in the second array and have the elements added to the end. Hopefully I am making sense.

Posting my attempt to code this method along with an example of what the output is, and what it is supposed to be.

EDIT: data is an instance variable within this class.

My code:

    public void append(double[] d)
{
    double[] temp = new double[data.length];
    for (int i=0; i<data.length;i++)
    {
        temp[i] = data[i];
    }

    data= new double[temp.length+d.length];
    for (int z=0; z<temp.length; z++)
    {
        data[z]=temp[z];
    }

    for (int t=0; t<d.length;t++)
    {
        data[t]=d[t];
    }
}

My output:

 stat1 data = []  
 stat1 data = [50.0, 60.0]  
 stat1 data = [70.0, 80.0, 0.0, 0.0]  
 stat1 data = [90.0, 100.0, 0.0, 0.0, 0.0, 0.0]  
 //null error comes

What it is supposed to be:

 stat1 data = []   
 stat1 data = [50.0, 60.0]   
 stat1 data = [50.0, 60.0, 70.0, 80.0]   
 stat1 data = [50.0, 60.0, 70.0, 80.0, 90.0, 100.0]   
 stat1 data = [50.0, 60.0, 70.0, 80.0, 90.0, 100.0, 100.0, 110.0]   
 stat1 data = [50.0, 60.0, 70.0, 80.0, 90.0, 100.0, 100.0, 110.0]  
 stat1 data = [100.0, 110.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]  
有帮助吗?

解决方案 2

You might want to change the second part of your loop.

 for (int t=0; t<d.length;t++)
    {
        data[t+temp.length]=d[t];
    }

其他提示

for the second loop the counter should start from the end of data

int newCounter = 0;
for (int t=temp.lenght; t<data.length;t++)
{
    data[t]=d[newCounter++];
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top