简体   繁体   English

返回对象数组中的单个对象

[英]return a single object in an object array

I'm new to programming and I was wondering how do you return a single object from an object array This is the part of the code I'm having trouble in: 我是编程新手,我想知道如何从对象数组返回单个对象,这是我遇到麻烦的部分代码:

public Class methodName(){
    x = 3;
    if(array[x] != null){
        Class y = array[x];
    }
    return y;
}

it gives me an error on the "y" 它给我关于“ y”的错误

y cannot be resolved to a variable

Because y is declared inside of the if , it's unavailable outside of the if . 因为yif内部声明,所以在if外部不可用。

Declare it outside of the if with a default value, then reassign it inside the if : 使用默认值在if外部声明它,然后在if内部重新分配它:

public Class methodName(){
    x = 3;
    Class y = null; // Defaults to null if not reassigned later
    if(array[x] != null){
        y = array[x]; // Reassign the pre-declared y here if necessary
    }
    return y;
}

This will return the default null if array[x] == null . 这将返回默认null ,如果array[x] == null

Look up how variables are scoped to learn what's going on here. 查找变量的范围,以了解此处发生的情况。 Basically, if a variable is declared within a {} , it can't be used outside of the {} (although that's a gross over-simplification). 基本上,如果在{}内声明了变量,则不能在{}之外使用它(尽管这过于简化了)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM