当我编码时,我在ObjectArray.main(ObjectArray.java:24)上得到一个异常作为“线程中的异常”main“java.lang.NullPointerException”
当我在eclipse中执行以下代码时:当我编码时,我在ObjectArray.main(ObjectArray.java:24)上得到一个异常作为“线程中的异常”main“java.lang.NullPointerException”,java,arrays,eclipse,nullpointerexception,Java,Arrays,Eclipse,Nullpointerexception,当我在eclipse中执行以下代码时: class Account { int a, b; public void setData(int c, int d) { a=c; b=d; } public void showData() { System.out.println("Value of a: "+a); System.out.println("Value of b: "+b); } } public class Object
class Account
{
int a, b;
public void setData(int c, int d)
{
a=c;
b=d;
}
public void showData()
{
System.out.println("Value of a: "+a);
System.out.println("Value of b: "+b);
}
}
public class ObjectArray
{
public static void main(String args[])
{
Account obj[] = new Account[2];
//obj[0]=new Account();
//obj[1]=new Account();
obj[0].setData(1, 2);
obj[1].setData(3, 4);
System.out.println("For Array Element 0:");
obj[0].showData();
System.out.println("For Array Element 1:");
obj[1].showData();
}
}
我得到以下例外情况:
线程主java.lang.NullPointerException中出现异常
位于ObjectArray.mainObjectArray.java:24
请给我一个建议,为什么会发生这个错误
Account obj[] = new Account[2];
它将为“Account”类的2个对象分配内存。要初始化这些内存位置,您必须选择以下任一方式:
Account obj[] = {new Account(), new Account()};
obj[0]=new Account();
obj[1]=new Account();
因为你注释掉了初始化,这会阻止NPE?