Quote:
However when I try to run the following I get the error "variable output might not have been initialized":
This is because this code is beyond the compiler understanding.
The compiler see 3 independent conditions but is unable to understand that they are complementary and 1 will do.
Because the 3 conditions are complementary, the third is overkill and the same logical result can be achieved with:
public int close10(int a, int b) {
int output;
if (Math.abs(a - 10) > Math.abs(b - 10)) {
output = b;
}
else if (Math.abs(a - 10) < Math.abs(b - 10)) {
output = a;
}
else {
output = 0;
}
return output;
}