When you create an array, it will be filled by the default value of the element it contains. Since Animal
is an Object
, then it will be filled by null
values, and you cannot use any variable which has null
value. Since you're just filling animal[i][0]
in your current code, you won't get any problem. But it will appear when you try to access to animal[i][1]
. This happens in Display
method:
public static void Display(animal x[][], animaltype y[]) {
System.out.println("Your animals are..");
for (int m = 0; m < x.length; m++) {
System.out.printf("Following are the name and the breed of %s ",
y[m].getAnimalType());
System.out.println();
for (int n = 0; n < x[m].length; n++) {
//you only filled elements in x[m][0]
//x[m][n] when n > 0 is null
//so you will get NullPointerException
System.out.printf(" %s", x[m][n].aname);
System.out.printf(" %s", x[m][n].abreed);
System.out.println();
}
}
}
A better option:
Use Animal[] addAnimal
instead, you don't need it to have it as an array of arrays:
public static void main(String[] args) {
System.out.println("How many animals you want to add..");
Scanner an = new Scanner(System.in);
int animalNumbers = an.nextInt();
animal[] addAnimal = new animal[animalNumbers];
animaltype[] at = new animaltype[animalNumbers];
for (int i = 0; i < animalNumbers; i++) {
//at[i] = new animaltype();
//Animalcat = at[i].getAnimalType();
Animalcat = new animaltype();
//for (int j = 0; j < 1; j++) {
// addAnimal[i][j] = new animal();
//}
addAnimal[i] = Animalcat;
}
Display(addAnimal, at);
}
//modify Display method accordingly
A better option:
Use List<Animal>
backed by ArrayList<Animal>
instead of Animal[]
. List
let's you handle a list of elements that grows dynamically.
public static void main(String[] args) {
System.out.println("How many animals you want to add..");
Scanner an = new Scanner(System.in);
int animalNumbers = an.nextInt();
List<Animal> animals = new ArrayList<Animal>();
for (int i = 0; i < animalNumbers; i++) {
Animalcat = new animaltype();
animals.add(Animalcat);
}
Display(animals);
}
//modify Display method accordingly