HelloMyNameIsRay
HelloMyNameIsRay

Reputation: 73

adding objects to an empty array in Java

I've been doing an exercise for class inheritance & abstract classes. I feel pretty confident with those two concepts, but as the title suggests, I'm (still) having trouble with adding objects to an array of type class.

The problem is as follows: there are 3 main types of files,

  1. a class Zoo file (contains main method)
  2. an abstract class animal file
  3. and any number of specific animals (cow, horse, whatever) which are derived classes of, you guessed it, class animal.

Class Zoo

public class Zoo 
{

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


Zoo()
{
    actual_num_animals = 0;
    num_cages = 20;
}

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.
//In otherwords, it calls the makeNoise() method 
//for all animals in the zoo.
public void make_all_noises()
{
    for(int i = 0; i < actual_num_animals; i++)
    {
        animals[i].makeNoise();
        System.out.print("! ");
    }
}

//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++)
    {
        animals[i].toString();
        System.out.print(" ");
    }
}

 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();  

    }
}

My problem resides within the add method here. I am continually getting a null pointer exception at the first if statement

if(animals[i] != null && animals[i].equals(a) == true)

as well as the first time this add method is being called within the main method. Clearly, there is something wrong with this condition, and likely the else-if condition that accompanies it.

For the life of me I can't understand, it's not working. What's worse is that I encountered a similar problem on a previous exercise here:

Class Inheritance in Java

The if and else-if condition written for class Zoo follows the exact same format in the add function outlined in this previous question, which is the most puzzling point of all. Any ideas you guys?

Lastly, for reference, though I doubt you'll need it, I'll include the animal class file and a derived class cow file below:

Abstract Class Animal

public abstract class Animal
{
private String name;
private double weight;
private int age;

Animal()
{
    name = "noName";
    weight = 0;
    age = 0;
}

Animal(String n, double weight, int age)
{
    name = n;
    this.weight = weight;
    this.age = age;
}

abstract String makeNoise();

String getName()
{
    return name;
}

double getWeight()
{
    return weight;
}

int getAge()
{
    return age;
}

public String toString()
{
    return name + ", weight: " + weight + "age: " + age;
}

}

Derived class Cow

public class Cow extends Animal 
{
private int num_spots;

Cow()
{
    super();
    num_spots = 0;
}
Cow(String name, double weight, int age, int num_spots)
{
    super(name, weight, age);
    this.num_spots = num_spots;
}

String makeNoise() 
{
    return "Moooo";
}

public String toString()
{
    return getName() + ", weight: " + getWeight() + "age: " + getAge() +
            "num spots: " + num_spots;
}
}

Upvotes: 1

Views: 21337

Answers (2)

earcam
earcam

Reputation: 6682

Add a line to your Zoo constructor to initialize the array:

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

You probably want to implement equals() as well (the "Bloch way" is a good implementation).

Upvotes: 2

Alberto Zaccagni
Alberto Zaccagni

Reputation: 31560

It seems to me that you never initialize

private Animal[] animals;

you should do

animals = new Animal[tot];

where tot is the number of total animals you are going to put in there. Note that you might want an ArrayList instead of an array, for example to avoid giving a starting dimension.

Upvotes: 0

Related Questions