java - 在适当的地点返回

标签 java return

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

相关文章:

java - 客户端 Axis 1.2 中 JDK5 Enum 的自定义序列化

java - 如何在使用RentrantLock完成所有三个 map 的初始化之前避免读取,并在更新完成后返回更新的 map 集?

java - 如何过滤 ListView ?

java - 扩展 StackView 或 AdapterViewAnimator 似乎是不可能的

java - GWT TextArea onBlur 未被调用

c++ - 如何使用方法返回指向对象结构的指针?

c++ - 返回一个空的 C 字符串

python - 矩阵从 C 函数到 Python

java - 根据条件从方法返回 boolean 值或整数

cocoa - 在 cocoa 中选择后如何在标签上返回文件名?