Array of Classes NullPointerException

后端 未结 8 1733
悲&欢浪女
悲&欢浪女 2020-12-12 05:17

This is Element class:

public class Element {

    private String elementName;
    private int atomicNumber;
    private String Symbol;
    priv         


        
相关标签:
8条回答
  • 2020-12-12 05:46

    you have only initialized the Element Array but never initialized its elements,

            Element[] element = new Element[103];
        element[0].setElementName("H");// this cause NPE as element[0] is null
    

    You need to initialize the elements like below:

          Element[] element = new Element[103];
           element[0] = new Element();
          element[0].setElementName("H");
    
    0 讨论(0)
  • 2020-12-12 05:47

    When you create an array of objects all it's elements are initialized to null. You simply have to create a new Element object and add it to the array like this:

    Element[] elems = new Element[100];
    elems[0] = new Element();
    elem[0].setElementName("asdf");
    
    0 讨论(0)
提交回复
热议问题