0

I have this program which has a class Ant where:

The default constructor initialises the instance variables queens to only 1 queen named “Beth” and colonySize to 100,000.

The defined constructor takes in two parameters and initialises the corresponding instance variables.

The method display, shows the information about an ant in the format below:

This ant colony has the following queens:
Queen 1: Beth
The colour of the ants: black
The approximate colony size: 100000

Here is what I have done:

public class Ant {

private String[] queens;
private String colour= "black";
private int colonySize;


public Ant(){
    queens[0]= "Beth";
    colonySize= 100000;
}

public Ant(String[] queens, int colonySize){
    this.queens[0]= queens[0];
    this.colonySize= colonySize;
}

public void display(){
    System.out.println("Queen 1: "+ this.queens[0]);
    System.out.println("Colour of the ants: "+colour);
    System.out.println("The size of the colony: "+ this.colonySize);
   }
}

The prob is arising when I am calling it in the main.

Main Class

public class MainAnts {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

       Ant obj= new Ant();
       obj.display();

    }

}

I am getting a Null Pointer Exception (because I suppose that's not the right way to call the display method in the main since it has an array variable).

Tia
  • 1,220
  • 5
  • 22
  • 47
  • Stepping through the code with a debugger might help. Thats how most other people fix their code. –  Jan 19 '17 at 18:39
  • 1
    Java Arrays are fixed with the size you declare/construct them. Your queens is empty. Simplest fix is: `private String[] queens = {""};` but see the answer from Robert Kasperczyk for a more thorough answer. – John Hascall Jan 19 '17 at 18:44

1 Answers1

1

Problem is that you never initialize your queens array. If you want to use ordinary array with fixed length then do:

    public Ant() {
        queens = new String[1000] //or whatever size you want
        queens[0] = "Beth";
        colonySize = 100000;
    }

Or you may want to use ArrayList:

    private List<String> queens;
    private String colour = "black";
    private int colonySize;


    public Ant() {
        queens = new ArrayList<>();
        queens.add("Beth");
        colonySize = 100000;
    }
    public void display() {
        System.out.println("Queen 1: " + this.queens.get(0));
        System.out.println("Colour of the ants: " + colour);
        System.out.println("The size of the colony: " + this.colonySize);
    }