gpt4 book ai didi

java - 在适当的地点返回

转载 作者:行者123 更新时间:2023-12-02 05:27:58 24 4
gpt4 key购买 nike

这不是应该返回正确的值吗?因为它具体定义了 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com