She :
class Solution {
public int[] Test(int[] x, int target) {
target = 100;
int i;
int j;
int sum;
for (i = 0; i > 3; i++) {
for (j = 0; j > 3; j++) {
sum = x[i] + x[j];
if (sum == target) {
return x[i];
return x[j];
}
}
}
}
}
I am trying to write a code to return 2 elements (from an array) which give me the target integer 100 when summed. I keep getting the following 2 errors:
incompatible types: int cannot be converted to int[]
return x[i];
incompatible types: int cannot be converted to int[]
return x[j];
Andrew Tobilko :
return new int[]{x[i], x[j]};
You want to return an array int[]
, not a single int
value.
return x[i];
return x[j];
doesn't make any sense because a return
statement immediately interrupts the flow (returns control to the invoker) making the following statements unreachable.
You are also missing a return statement at the end. When target
hasn't been met, you still have to return something from the method.
It could be an empty array:
return new int[0];
However, usually, we throw an exception saying the given arguments didn't make the method work:
throw new IllegalArgumentException("The target wasn't met for the given input.");