Reputation: 45
Isn't this supposed to return correct value? as it specifically defines int[] temp
? However, it says temp
is not resolved. so I had to put another return temp
inside if
and change the last return
inside else
statement so there were two returns as a result. If I set values inside if and else, couldn't I return it outside?
public int[] maxEnd3(int[] nums) {
if (nums[0] > nums[2]) {
int[] temp = {nums[0],nums[0],nums[0]};
}
else {
int[] temp= {nums[2],nums[2],nums[2]};
}
return temp;
}
Upvotes: 0
Views: 32
Reputation: 1307
You didn't declare temp in the correct scope. Try this:
public int[] maxEnd3(int[] nums) {
int []temp = new int[3];
if (nums[0] > nums[2]) {
temp[0] = nums[0];
temp[1] = nums[0];
temp[2] = nums[0];
}
else {
temp[0] = nums[2];
temp[1] = nums[2];
temp[2] = nums[2];
}
return temp;
}
Or this:
public int[] maxEnd3(int[] nums) {
int []temp;
if (nums[0] > nums[2]) {
temp = new int[]{nums[0],nums[0],nums[0]};
}
else {
temp = new int[]{nums[2],nums[2],nums[2]};
}
return temp;
}
When you declare it inside the if statement, it's only valid between the declaration line and the closing brace.
Upvotes: 2