I am getting an error:
java.lang.ArrayIndexOutOfBoundsException: -1
and it refers to method inject:
deque[back] = x;
I also have methods for push and pop which add and remove items at the front but those work fine.
The idea is to use an array-based implementation as deque, where inject and eject insert item at the back and remove item at the back.
public void inject(int x){
if (elementCount == size){
System.out.println("The Deque is Full");
} else {
deque[back] = x;
back = (back - 1) % size;
elementCount ++;
}
}
public class Deque {
int[] deque;
int front;
int back;
int size;
int elementCount;
public Deque(int s){
size = s;
deque = new int[size];
front = 1;
back = 0;
elementCount = 0; //n of elements
}
public int getRear(){
return deque[back];
}
public int getFront(){
return deque[front];
}
public void inject(int x){
if (elementCount == size){
System.out.println("The Deque is Full");
} else {
deque[back] = x;
back = (back - 1) % size;
elementCount ++;
}
}
public void eject(){
if (elementCount == 0){
System.out.println("The deque is empty");
}else{
back = (back + 1) % size;
elementCount--;
}
}
}
You have in multiple places:
That doesn't work like you think it does when
back
is originally0
, where it becomes-1 % size
, which is usually-1
. In the places where it appears, you should instead use: