Results 1 to 2 of 2

Thread: Java arrays

  1. #1
    tomcribb is offline Member
    Join Date
    Mar 2014
    Rep Power

    Default 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};


    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;
    {return null;}

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Voorschoten, the Netherlands
    Blog Entries
    Rep Power

    Default Re: Java arrays

    Why all the fiddling in the body of your for-loop? 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,

    The only person who got everything done by Friday was Robinson Crusoe.

Similar Threads

  1. Replies: 0
    Last Post: 05-03-2012, 12:55 AM
  2. Arrays in Java
    By manideep.d132 in forum Reviews / Advertising
    Replies: 2
    Last Post: 02-22-2012, 10:04 AM
  3. Arrays.sort... why sorting all arrays in class?
    By innspiron in forum New To Java
    Replies: 6
    Last Post: 03-23-2010, 02:40 AM
  4. java arrays
    By miko5054 in forum New To Java
    Replies: 15
    Last Post: 03-18-2010, 06:17 PM
  5. Arrays in Java
    By hiranya in forum New To Java
    Replies: 3
    Last Post: 07-30-2007, 09:10 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts