VERY new to java (first class of the intro course) and am having some trouble with writing a function that replaces each element in an array with the same integer but negative. I wrote this code:
int negation(int[] x) {
for (int i = 0; i < x.length; i ) {
if (x[i] != 0)
x[i] = -x[i];
}
return x;
}
but when executing it get the error
Expression has type int[], but an expression of type int was expected
on line 6. Not sure what this means exactly as I thought putting 'int[] x' made sure an array was expected, but apparently that isn't enough. Do I need to declare x as an array anywhere else?
CodePudding user response:
You're returning x
which is of type int[]
but your method is declared as returning int
.
Declaring your method as returning int[]
by changing it to int[] negation(int[] x)
should do it.
CodePudding user response:
Try this
int[] negation(int[] x)
Returning just x
should have the matching returning type in the function declaration.
If you return x[0]
for example it would match the function declaration.