The following code returns a new array containing the componentwise sum of its arguments (assuming their length is the same), for example if the input arrays are {0,1,2} and {2,2,3} then the out out will be {2,3,5} and if the input arrays have different numbers of elements, the method should return null.
public class Sum
{
public static double[] sum(double a[], double b[]){
if (a.length != b.length)
return null;
int[] s = new double[a.length];
for(int i=0; i<a.length; i++)
s[i] = a[i] + b[i];
return s;
}
public static void main(String[] args) {
//calling the method to seek if compiles
double[] results = Sum.sum(new double[] {0,1,2} + {2,2,3});
//printing the results
System.out.println(java.util.Arrays.toString(results));
}
}
As I have mentioned before normally when I run this program code above I supposed to have {2,3,5} as result, but I am getting nothing. In fact I cannot able to compile it in BlueJ, I am keep getting the error message saying: illegal start of expression for this line: double[] results = Sum.sum(new double[] {0,1,2} + {2,2,3});
So I assume I did syntax error, but I am not too sure, how can I get rid of it, any suggestions?
There are two problems in your code:
The
+
operator is allowed for primitive numeric types only. In this line of code:You're trying to apply
+
operator fordouble[]
variables, which is not allowed, thus getting the exception. Since the method already accepts 2 argumentsdouble[]
, then send bothdouble[]
s by separating them using comma,
.:This line of code:
You cannot initialize an array of primitive type with an array of another primitive type.
int[]
anddouble[]
are complete different classes. So, instead change the type declaration for your variable:More info: