Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从非静态方法访问作为实例变量的对象数组?_Java_Arrays_Object - Fatal编程技术网

Java 如何从非静态方法访问作为实例变量的对象数组?

Java 如何从非静态方法访问作为实例变量的对象数组?,java,arrays,object,Java,Arrays,Object,即使我的构造函数实例化了对象数组,我的程序也会给我空指针。为什么我会有例外? 下面是我的代码:当main方法运行比较行时,它会给我一个空指针异常。我不能以这种方式访问我的对象吗 class MPLTest{ int n; MPL []std; MPLTest(){ System.out.println("Enter number of Standards: "); Scanner in = new Scanner(System.in); n=in.nextInt();

即使我的构造函数实例化了对象数组,我的程序也会给我空指针。为什么我会有例外? 下面是我的代码:当main方法运行比较行时,它会给我一个空指针异常。我不能以这种方式访问我的对象吗

class MPLTest{
int n;
MPL []std;
MPLTest(){
    System.out.println("Enter number of Standards: ");
    Scanner in = new Scanner(System.in);
    n=in.nextInt();
    MPL []std = new MPL[n];
    for(int i=0;i<n;i++){
        System.out.println("Enter the number of students for standard "+(i+1));
        std[i]=new MPL(i+1,in.nextInt());
    }

}
public static void main(String [] args){

    MPLTest test = new MPLTest();
    System.out.println("The standard scoring the highest total marks is "+test.findBestClass());

}
int findBestClass(){
    int best=0;
    for(int i=1;i<n;i++){
        if(std[i].findTotal()>std[best].findTotal()) //the exception is here
            best=i;
    }
    return best+1;
}
类测试{
int n;
MPL[]std;
MPLTest(){
System.out.println(“输入标准数量:”);
扫描仪输入=新扫描仪(系统输入);
n=in.nextInt();
MPL[]std=新的MPL[n];
对于(int i=0;i
→   MPL[]std;
MPLTest(){
System.out.println(“输入标准数量:”);
扫描仪输入=新扫描仪(系统输入);
n=in.nextInt();
→       MPL[]std=新的MPL[n];

这被称为。块内的
std
是一个局部变量,它隐藏了一个名为
std

的类似但不同的字段,您得到了一个
NullPointerException
,因为全局实例数组未在构造函数中初始化。您已经声明了
std[]
在类中,但在构造函数中,您声明了一个新的数组,它是本地数组,类型为
MPL
。要初始化实例数组,请替换该行

MPL[] std = new MPL[n]; //creates a local variable

std = new MPL[n]; //points to the global variable
这类似于使用实例变量
int n
。在构造函数中,您不写入

int n = in.nextInt();
但是


因为已经声明了
n
。用同样的方法初始化数组。

这一行MPL[]std=new-MPL[n];应该是std=new-MPL[n];谁否决了这个?没有投票的答案更好,向上投票的答案(注释)更差。怎么回事?
n = in.nextInt();