[英]Getting Exception in thread “main” java.lang.NullPointerException
While running this code 在运行此代码时
public class Main
{
public int a;
public int b;
public static void main(String []args)
{
Main []ary=new Main[26];
int i;
for(i=0;i<26;i++)
{
ary[i].a=0;
ary[i].b=i;
}
}
}
I am getting the following error.. 我收到以下错误。
Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:11)
I created an array of objects for the same class and trying to use its instance variables 我为同一类创建了一个对象数组,并尝试使用其实例变量
Though I searched for it, i am not able to find the mistake.. 虽然我已经搜索了,但是我找不到错误。
Main []ary=new Main[26];
You declared array
not assigned values in it. 您声明
array
未分配值。
So in memory, you array looks like Main []ary={null,null ...., null};
因此,在内存中,数组看起来像
Main []ary={null,null ...., null};
Thrown when an application attempts to use null in a case where an object is required.
当应用程序在需要对象的情况下尝试使用null时抛出。 These include:
这些包括:
It's like null.a
which causes NullPointerException
. 就像
null.a
会导致NullPointerException
。
for(i=0;i<26;i++)
{
Main m = new Main();
m.a =0;
m.b =i;
ary[i]= m;
}
Main []ary=new Main[26];
int i;
for(i=0;i<26;i++)
{
ary[i]=new Main();
ary[i].a=0;
ary[i].b=i;
}
This will work :) 这将工作:)
You need to create an instance for each of the array's entries in order to access it : 您需要为每个数组条目创建一个实例才能访问它:
for(i=0;i<26;i++)
{
ary[i] = new Main(); // Otherwise ary[i] is null and will cause an exception on the following line
ary[i].a=0;
ary[i].b=i;
}
ary[i] is null ary [i]为空
public class Main
{
public int a;
public int b;
public static void main( String[] args )
{
Main[] ary = new Main[26];
int i;
for ( i = 0; i < 26; i++ )
{
ary[i]=new Main();//<---(here ary[i] was null)
ary[i].a = 0;
ary[i].b = i;
}
}
}
You just created an array that can hold instances of Main
, but you didn't initialize the contents, so all elements of the array are null
. 您刚刚创建了一个可以容纳
Main
实例的数组,但是没有初始化内容,因此该数组的所有元素均为null
。 Do ary[i]= new Main()
before assigning the values. 在分配值之前,先执行
ary[i]= new Main()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.