1

Before I begin, here is what I'm working on

  1. a class named "Zoo" which contains the main method
  2. an abstract class named "Animal"
  3. Several extended classes for class "Animal"

I have the code for "Zoo" posted at the bottom. I keep getting the following error when I run it

 Exception in thread "main" java.lang.NullPointerException
 at zoo.Zoo.add(Zoo.java:27)
 at zoo.Zoo.main(Zoo.java:90)"

If I comment out the second zoo part it works fine. Why am I getting an error for the 2nd zoo? And what can I do to fix it?

public class Zoo 
{

private int actual_num_animals;
private int num_cages;
private Animal[] animals;


Zoo()
{
actual_num_animals = 0;
num_cages = 20;
animals = new Animal[num_cages];
}

Zoo(int num_cages)
{
this.num_cages = num_cages;
}

// adds an animal to Zoo
public void add(Animal a)
{
for(int i = 0; i < num_cages; i++)
{
    if(animals[i] != null && animals[i].equals(a) == true)
    {
        System.out.println(a.getName() + " is already in a cage!");
        break;
    }
    else if(animals[i] == null)
    {
        animals[i] = a;
        actual_num_animals++;
        break;
    }
}

}

// returns the total weight of all animals in zoo
public double total_weight()
{
double sum = 0;

for(int i = 0; i < actual_num_animals; i++)
{
    sum += animals[i].getWeight();
}
return sum;
}

//Print out the noises made by all of the animals.
public void make_all_noises()
{
for(int i = 0; i < actual_num_animals; i++)
{
    animals[i].makeNoise();
    System.out.println( animals[i].makeNoise());
}
}

//prints the results of calling toString() on all animals in the zoo.
public void print_all_animals()
{
for(int i = 0; i < actual_num_animals; i++)
{
    System.out.println(animals[i]);
}
}

public static void main(String[] args)
{
Zoo z = new Zoo();
Snake sly = new Snake("Sly", 5.0 , 2, 2);
Snake sly2 = new Snake("Slyme", 10.0 , 1, 2);
Cow blossy = new Cow("Blossy", 900., 5,  10);
Horse prince = new Horse("Prince", 1000., 5, 23.2);

// Following not allowed because Animal is abstract
//Animal spot = new Animal("Spot", 10., 4);

z.add(sly);
z.add(sly2);
z.add(blossy);
z.add(prince);

z.make_all_noises();
System.out.println("Total weight = " + z.total_weight());
System.out.println("**************************");
System.out.println("Animal Printout:");
z.print_all_animals();  

System.out.println("********* Now we will make the Second Zoo");
Zoo z2 = new Zoo(5);
z2.add(sly);
z2.add(sly2);
z2.add(blossy);
z2.add(prince);
z2.add( new Horse("Warrior", 1200, 6, 25.3));
z2.add( new Horse("Harry", 1100, 4, 21.3));
System.out.println("Total weight of z2="+z2.total_weight());
z2.make_all_noises();
z2.print_all_animals(); 
}
}

If needed I can post the "Animal" class and the other classes that extend from it.

Jman2
  • 11
  • 1

0 Answers0