Null pointer exception for Array of Objects

后端 未结 4 903
长情又很酷
长情又很酷 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条回答
  • 2020-12-22 10:10

    replace

    arrayOfSpotlights[i].turnOn();
    

    with

    arrayOfSpotLights[i] = new Spotlight();
    arrayOfSpotlights[i].turnOn();    
    

    The line

    arrayOfSpotlights =  new spotlight[N];
    

    will create an array of spotlights. It will however not populate this array with spotlights.

    0 讨论(0)
  • 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;
        }
    }
    
    0 讨论(0)
  • 2020-12-22 10:18

    When you do "arrayOfSpotlights = new spotlight[N];" you init an array of length N, what you need to do is also init each object in it:

    for i=0; i<N; i++
        arrayOfSpotlights[i] = new spotlight();
        arrayOfSpotlights[i].turnOn();
    

    Hope I'm correct :)

    0 讨论(0)
  • 2020-12-22 10:29

    You declared the array arrayOfSpotlights, but didn't initialize the members of the array (so they are null - and you get the exception).

    Change it to:

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

    and it should work.

    0 讨论(0)
提交回复
热议问题