Results 1 to 2 of 2

Thread: Java arrays

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

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

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

  2. #2
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,335
    Blog Entries
    7
    Rep Power
    20

    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,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

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, 09: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, 01:40 AM
  4. java arrays
    By miko5054 in forum New To Java
    Replies: 15
    Last Post: 03-18-2010, 05: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
  •