类数组NullPointerException [英] Array of Classes NullPointerException

查看:43
本文介绍了类数组NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是 Element 类:

public class Element {

    private String elementName;
    private int atomicNumber;
    private String Symbol;
    private double atomicWeight;

    public Element()
    {

    }

    public String getElementName()
    {
        return elementName;
    }
    public int getAtomicNumber()
    {
        return atomicNumber;
    }
    public String getSymbol()
    {
        return Symbol;
    }
    public double getAtomicWeight()
    {
        return atomicWeight;
    }
    public void setElementName(String elementName)
    {
        this.elementName = elementName;
    }
    public void setAtomicNumber(int atomicNumber)
    {
        this.atomicNumber = atomicNumber;
    }
    public void setSymbol(String Symbol)
    {
        this.Symbol = Symbol;
    }
    public void setAtomicWeight(double atomicWeight)
    {
        this.atomicWeight = atomicWeight;
    }

}

我正在尝试创建此类的 Array ,这是我的 mainU.java 类:

I am trying to make an Array of this class, this is my mainU.java class:

public class mainU {

    public static void main(String[] args){     

            Element[] element = new Element[103];

        element[0].setElementName("H");
        String s = element[0].getElementName();

        System.out.println(s);

}

问题是我遇到此错误:

Exception in thread "main" java.lang.NullPointerException
    at mainU.main(mainU.java:14)

任何人都可以告诉我我得到这样一个错误的原因吗?我使我的程序尽可能简单,以便您能够帮助我.

Anyone can tell me the reason i'm getting such an error? I made my program as simple as possible in order for you to be able to help me.

推荐答案

问题出在以下部分:

Element[] element = new Element[103];
element[0].setElementName("H");

您访问第一个元素而不在此之前创建它.您创建了数组,但是它不自动包含所使用类型的新对象,因此必须显式声明这些对象,例如:

Your accessing the first element without creating it before that. you create the array but it doesnt containt automatically new objects of the type used, you have to declare these explicitly, for example:

element[0] = new element();

然后您可以使用该对象.

And then you can use the object.

这篇关于类数组NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆