0

I have an array, in this case double [] v, which will take 4 values (0, 1, 2, 3).

I need to multiply each element of the array by "c" and store the result of each one back in a new array. I have tried it but i always end up getting the error message that double cannot be converted to double []. I can't figure out why and the examples here in SO have not helped.

public class q7_2014 {
    public static double [] multiply ( double [] v, double c){
        double [] newArray = new double [4];
        double multiply = 0;

        for (int i = 0; i < v.length; i++){
            multiply = v[i]*c;



            System.out.println(multiply);

        }



        return newArray;

    }

}

The code works fine and prints what is supposed to go into the array, but I just can't figure out how.

what am I missing? (the print statement was just to check if the code was working as expected in terms of results). Thanks

Miguel
  • 99
  • 12
  • I don't believe this is a duplicate, since i'm not asking how to initialize an array since you can see in my code that I do that on the second line. I'm simply asking how to store the multiplication of each element of one array into another one. Thank you anway – Miguel May 27 '18 at 01:33

3 Answers3

1

You need to set the result of the multiplication back into newArray

public class q7_2014 {
    public static double [] multiply (double[] v, double c){
        double[] newArray = new double[v.length];
        // You don't need multiply since
        // you need to return newArray
        //double multiply = 0;

        for (int i = 0; i < v.length; i++){
            newArray[i] = v[i] * c;
            // uncomment if you need to print the current value
            // System.out.println(newArray[i]);
        }
        return newArray;
    }
}
StaticBeagle
  • 4,695
  • 2
  • 22
  • 30
1

Try this code:

public class q7_2014 {
public static double [] multiply ( double [] v, double c){
    double [] newArray = new double [4];
    for (int i = 0; i < v.length; i++){
        newArray[i] = v[i]*c;
        }

    return newArray;
   }
}
Nirel
  • 1,734
  • 1
  • 12
  • 24
1

You should store the results of your multiplication in newArray. Also, you should size newArray by the passed in array v length. Like,

public static double[] multiply(double[] v, double c) {
    double[] newArray = new double[v.length];
    for (int i = 0; i < v.length; i++) {
        newArray[i] = v[i] * c;
    }
    return newArray;
}

And in Java 8+, you could produce the same result with a single line of code using a DoubleStream and a map operation. Like,

public static double[] multiply(double[] v, double c) {
    return DoubleStream.of(v).map(d -> d * c).toArray();
}
Elliott Frisch
  • 183,598
  • 16
  • 131
  • 226
  • Thanks for your suggestion. In fact i was just missing newArray "[i]" . Im sure your single line of code would also work, but since im still new to Java i'm not familiar with this syntax. – Miguel May 27 '18 at 01:29