【问题标题】:I am getting an Exception as "Exception in thread "main" java.lang.NullPointerException at ObjectArray.main(ObjectArray.java:24)" while i am coding [duplicate]我在编码时收到一个异常为“线程“主”java.lang.NullPointerException at ObjectArray.main(ObjectArray.java:24) 中的异常”[重复]
【发布时间】:2017-05-03 10:56:02
【问题描述】:

当我在 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 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();
  }
}

我收到以下异常:

线程“main”中的异常 java.lang.NullPointerException 在 ObjectArray.main(ObjectArray.java:24)

请给我建议为什么会发生这个错误?

【问题讨论】:

  • 因为您确实注释掉了会阻止NPE的初始化?

标签: java arrays eclipse nullpointerexception


【解决方案1】:
Account obj[] = new Account[2];

它将为“Account”类的 2 个对象分配内存。要初始化这些内存位置,您必须选择任何一种方式:

Account obj[] = {new Account(), new Account()};
obj[0]=new Account();
obj[1]=new Account();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-09
    • 2013-08-25
    • 1970-01-01
    相关资源
    最近更新 更多