Question

I am trying to write a method that takes two arrays as parameter, and than return the sum of them. But I have two problems firstly I have error now that is saying incompatible types and is showing the error at return s. The other question is how to add 0 values to one array if it is shorter than the other.

Cheers.

public class Question1d{
    public static void main (String [] args){
        double[] v = {1, 2, 3, 4, 5};
        double[] w = {5, 4, 3, 2, 1};
        double[] s;     
    }

    public static double add(double[] v, double[] w){
        int a;
        if (v.length >= w.length){
            a = v.length;
        }
        else{
            a = w.length;
        }
        double[] s = new double[a];
        for(int i = 0; i<=a; ++i){
            s[i] = v[i] + w[i];
        }
        return s;
    } 
}
Was it helpful?

Solution

You have declared your method as returning double (a single value) not double[] (an array of values).

To handle the zero values work out the length of the shortest and the longest arrays.

Declare your results array to the longest length.

Loop through from 0 to shortest adding the values together.

Loop through from shortest to longest just copying the value from the longer array.

OTHER TIPS

You're returning a double[], not a double like you stated.

Please check the updated code. you need to mention the return type as array in method.

public class Question1d{
    public static void main (String [] args){
        double[] v = {1, 2, 3, 4, 5};
        double[] w = {5, 4, 3, 2, 1};
        double[] s;  
        for(double d:Question1d.add(v, w))
        System.out.println(d);
    }

    public static double[] add(double[] v, double[] w){
        int a;
        if (v.length >= w.length){
            a = v.length;
        }

        else{
            a = w.length;
        }
        double[] s = new double[a];
        for(int i = 0; i<a; ++i){

            s[i] = v[i] + w[i];
        }
        return s;
    } 
}

2.it is not possible to update the size of any array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top