I have a section of code that is puzzling me. I define an integer array inside an if/else statement because the length of the array depends on the length of 2 inputs to the
You are declaring the output variable as a local variable inside each of the if/else statements. To fix this, declare it first outside then adjust it and return the results. This keeps it in the scope between the brackets { }
.
public String AddArrays(int [] arg1, int [] arg2) {
int L1 = arg1.length;
int L2 = arg2.length;
int[] output;
if (L1 > L2) {
output = new int[L2];
for (int i = 0; i < L2; i++) {
output[i] = arg1[i] + arg2[i];
}
} else {
output = new int[L1];
for (int i = 0; i < L2; i++) {
output[i] = arg1[i] + arg1[i];
}
}
String result = Arrays.toString(output);
return result;
}