
Java arrays
Hi Guys,
I need to create a method that returns a new array containing the componentwise sum of its arguments(if length is the same). For instance, if the input arrays are {0,1, 2} and {2, 2, 3} then the output is {0+2, 1+2, 2+3}, i.e. {2,3,5}.If the input arrays have different numbers of elements, the method should return null.
I came with something like this, however i dont know how to make a copy of an array from two arrays. My code obviously wont compile. Have you got any idea how to solve this? Many thanks
package whatever;
import java.util.Arrays;
public class hhhh {
public static void main(String[] args) {
double [] a = {1,2,3};
double [] b = {2,3,4};
System.out.println(sum(a,b));
}
public static double [] sum(double [] a, double [] b)
{
double [] sum;
for(int i= 0; i<a.length; i ++)
{
if (a.length == b.length)
{ sum = Arrays.copyOf(a, a.length);
return sum;
}
else
{return null;}
}
}
}

Re: Java arrays
Why all the fiddling in the body of your forloop? I'd use the following control flow in that method:
1) check if the lenghts of a and b are the same; if not, return null
2) create an array 'sum' of the same length.
3) add the corresponding elements of a and b and store them in sum
4) return sum after the previous steps are done.
kind regards,
Jos