Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

java - Array of Classes NullPointerException

This is Element class:

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;
    }

}

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);

}

The problem is that i'm getting this error:

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The Problem is in the part:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...