0

I have a manual implementation of a queue, which is supposed to enqueue 10 user inputted integers, however, whenever I try to enqueue something, it throws a NullPointerException. Here is my constructor and instance variables for the Queue class

private int [] data; //stores queue elements
private int front; //the element at the beginning of the queue
private int rear; //the element at the end of the queue
int maxCap; //max size possible for the queue
private int size; //size of the current queue

public Queue (int maxSize){
    int[] data = new int[maxSize];
    front = -1;
    rear = -1;
    maxCap = maxSize;
    size = 0;
}

My rear and front start off as -1 (which is empty queue), but in my enqueue method, the front and rear should be set to 0, and then the rear should increment by 1, so that the value that needs to get added to the queue can be added from the rear.

public int enqueue(int n) { 
    //where n is the item we want to add 
    if(isFull()){ //if the queue is full, we cannot add anything
        System.out.println("Cannot add item, queue is currently full.");
        return n;
    }

    else if(isEmpty()){ //checks to see if the front = rear = -1
        front = rear = 0;
        rear+=1;
    }

    else{
        rear+=1;
        rear %= maxCap;
    }

    data[rear] = n; 
    size ++;
    return n;
}

Any help would be greatly appreciated!

0 Answers0