0

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];
    }

}

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

6 Comments

what if i dont know the size [depends on the input]?
Then you have to wait to initialize it until you know the size or use a different data structure, which for java is the ArrayList. Arrays can't be resized dynamically.
@user1763553 You could initialize it in the constructor instead, or yeah, just use a collection.
@user1763553 in your example, since you are calculating the fibonacci sequence up to parameter x.last, you could initialize it inside: seq = new int[x.last].
the problem is that this is a sequence so i will never know its size even after putting some elements. i dont know when it will end so how will the ArrayList method be useful? and how to implement it? thanks!
|
2

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]

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.