这不是应该返回正确的值吗?因为它具体定义了 int[] temp
?但是,它说 temp
未解决。所以我必须在 if
中放置另一个 return temp
并更改 else
语句中的最后一个 return
,这样就有两个返回结果。如果我在 if 和 else 内部设置值,我不能将其返回到外部吗?
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;
}
最佳答案
您没有在正确的范围内声明 temp。 试试这个:
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;
}
或者这个:
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;
}
当您在 if 语句内声明它时,它仅在声明行和右大括号之间有效。
关于java - 在适当的地点返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25816947/