Java 如何从非静态方法访问作为实例变量的对象数组?
即使我的构造函数实例化了对象数组,我的程序也会给我空指针。为什么我会有例外? 下面是我的代码:当main方法运行比较行时,它会给我一个空指针异常。我不能以这种方式访问我的对象吗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();
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();