Java 准时返回

Java 准时返回,java,return,Java,Return,这不是应该返回正确的值吗?它具体定义了int[]temp?但是,它说,temp没有得到解决。因此,我不得不将另一个returntemp放在if中,并将最后一个return放在else语句中,因此有两个返回。如果我在If和else中设置值,我不能在外部返回它吗 public int[] maxEnd3(int[] nums) { if (nums[0] > nums[2]) { int[] temp = {nums[0],nums[0],nums[0]};

这不是应该返回正确的值吗?它具体定义了
int[]temp
?但是,它说,
temp
没有得到解决。因此,我不得不将另一个return
temp
放在
if
中,并将最后一个
return
放在
else
语句中,因此有两个返回。如果我在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语句中声明它时,它仅在声明行和右大括号之间有效