mardi 24 février 2015

Newbie at Java - why does this not compile?



Tearing my hair out with this now. It's my second program in Java and I tried to extend a simple Dog class into an array of Dog class. I cannot see what is wrong with this but the error I get is:


Exception in thread "main" java.lang.NullPointerException at Dogprint.main(Dogprint.java:5)



public class Dogprint {
public static void main(String[] args) {
Dog[] dog1 = new Dog[2];

dog1[0].setbreed("poodle");
dog1[0].setsize(2);
dog1[1].setbreed("Alsation");
dog1[1].setsize(5);

for (int i = 0; i < 2; i ++) {
System.out.println(dog1[i].getsize());
System.out.println(dog1[i].getbreed());
}
}
}


Class Dog:



class Dog {
private int size;
private String breed;

public void setbreed(String breed) {
this.breed = breed;
}

public void setsize(int size) {
this.size = size;
}

public int getsize() {
return size;
}

public String getbreed() {
return breed;
}
}



Aucun commentaire:

Enregistrer un commentaire