CSawy
CSawy

Reputation: 924

java array declaration

I get the error shown in the comment when I call my class's constructor (when I remove the array parts everything goes fine). Is this because of a wrong declaration of the array seq?

public class FibIt implements SeqIt{
    public int counter;
    public int ptr;
    public int [] seq;

    public FibIt(Fib x)
    {   counter=0;
        ptr=0;
        seq[0]=x.first1;         //gives me an error here saying Exception in 
                                     //thread "main" java.lang.NullPointerException
                                 //at FibIt.<init>(FibIt.java:9)
                                     //at Main.main(Main.java:6)
        seq[1]=x.first2;
        for (int i=2; seq[i-1]<=x.last; i++)
            {seq[i]=seq[i-1]+seq[i-2];}
    }
    @Override
    public int func2() {
        // TODO Auto-generated method stub
        ptr++;
        return seq[ptr-1];
    }

}

Upvotes: 0

Views: 376

Answers (3)

Austin
Austin

Reputation: 4929

You have to initialize your array, so something like public int[] seq = new int[10];

Then replace 10 with whatever size you need.

And I was just about to answer your question when @Jack posted a good solution. ArrayList<Integer> is pretty useful if you don't know the size of the array.

Upvotes: 6

Jack
Jack

Reputation: 133669

You need to initialize the array. One thing is declaration, other thing is inizialization.

int[] seq declares a variable of name seq which is an array of int. Then you need to effectively inizialize it by assigning to it a constructor for an array: new int[dimension]

Upvotes: 2

vels4j
vels4j

Reputation: 11298

Yes, you have only declared the array but not initilized.

public int [] seq = new int[anySize];

Upvotes: 1

Related Questions