Null pointer exception for Array of Objects

后端 未结 4 916
长情又很酷
长情又很酷 2020-12-22 09:55

I am new to using arrays of objects but can\'t figure out what I am doing wrong and why I keep getting a Null pointer exception. I am trying to create an Theatre class with

4条回答
  •  猫巷女王i
    2020-12-22 10:17

    You are not creating an spotlight objects.

    arrayOfSpotlights =  new spotlight[N];
    

    This just creates an array of references to spotlights, not the objects which are referenced.

    The simple solution is

    for (int i = 0; i < arrayOfSpotlights.length; i++) { 
        arrayOfSpotlights[i] = new spotlight();
        arrayOfSpotlights[i].turnOn();          
    }
    

    BTW You should use TitleCase for class names.

    You could write your class like this, without using cryptic code like 0 and 1

    public class Spotlight {
        private String state;
    
        public Spotlight() {
            turnOff();
        }
    
        public void turnOn() {
            state = "on";  
        }
    
        void turnOff() { 
            state = "off";
        }
    
        public String toString() {
            return "is " + state;
        }
    }
    

提交回复
热议问题