Array of Classes NullPointerException

后端 未结 8 1747
悲&欢浪女
悲&欢浪女 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");
    

提交回复
热议问题