Stack and Queue arrays returning wrong values - java

I've created stack and queue arrays which hold integers and have a max capacity of ten. I added the values 1-11 and then will remove and print each value until empty. The queue is not only printing 11 values, but also printing 1 instead of 11 for the first value. The stack however is only printing and removing the 10 values but is giving me an IndexOutBoundsException that is not being caught. Any idea why?
Output:
run:
Print queue:
11 2 3 4 5 6 7 8 9 10 11
Print stack:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at lab4.Stack.pop(Stack.java:44)
at lab4.Lab4.main(Lab4.java:54)
10 9 8 7 6 5 4 3 2 1
BUILD FAILED (total time: 0 seconds)
Main:
Queue queue = new Queue(10);
Stack stack = new Stack(10);
queue.insert(1);
queue.insert(2);
queue.insert(3);
queue.insert(4);
queue.insert(5);
queue.insert(6);
queue.insert(7);
queue.insert(8);
queue.insert(9);
queue.insert(10);
queue.insert(11);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.push(6);
stack.push(7);
stack.push(8);
stack.push(9);
stack.push(10);
stack.push(11);
System.out.println("Print queue: ");
while (!queue.isEmpty()) {
long n = queue.remove();
System.out.print(n + " ");
}
System.out.println("");
System.out.println("Print stack: ");
while (!stack.isEmpty()) {
Object value = stack.pop();
System.out.print(value + " ");
}
Stack.java
public class Stack {
private int[] stackArray; // Stack array of objects
private int maxSize = 10; // Max size of the stack
private int top; // top integer of stack
public Stack(int maxSize) {
stackArray = new int[maxSize];
top = -1;
}
public boolean isEmpty() {
return (top == maxSize); // true if stack is empty
}
public boolean isFull() {
return (top == maxSize - 1); // true if full
}
public int size() {
return (top + 1); // Return the # of items
}
public void push(int item) // put element into array
{
if (!isFull()) {
top++;
stackArray[top] = item;
}
}
public Object pop() {
if (!isEmpty()) {
top--;
return stackArray[top + 1];
} else
throw new IllegalStateException("Stack empty");
}
public Object peek() {
return stackArray[top];
}
public String toString() {
return "Size: " + maxSize + " Capcaity: " + top; // complete: show the size and capacity
}
}
Queue.java
public class Queue {
private int maxSize = 10;
private int[] queueArray;
private int front;
private int rear;
private int nItems;
// Constructor
public Queue(int s) {
queueArray = new int[maxSize];
front = 0;
rear = -1;
nItems = 0;
}
// Insert item at rear of queue
public void insert(int j) {
if (rear == maxSize - 1) { // Deal with wraparound
rear = -1;
}
queueArray[++rear] = j;
nItems++;
}
public int remove() {
int temp = queueArray[front++];
if (front == maxSize) {
front = 0;
}
nItems--;
return temp;
}
public int peekFront() {
return queueArray[front];
}
public int peekRear() {
return queueArray[front];
}
public boolean isEmpty() {
return (nItems == 0);
}
public boolean isFull() {
return (nItems == maxSize);
}
public int size() {
return nItems;
}
}

These are pretty simple fixes! For the queue, you need to set your maxSize to 11. This will allow you to print each number in the queue correctly without printing the 11 in front. Long story short, given you have 11 total elements in your queue, a max queue size of 11 is necessary.
public class Queue {
private int maxSize = 11;
private int[] queueArray;
private int front;
private int rear;
private int nItems;
}
Now, in terms of your stack, this was also a pretty simple fix. As of right now, your code is returning top == maxSize (or 10) when the stack is empty. This is causing an issue with the pop function. However, when the stack is empty, top should equal -1. So make sure to set top == -1 in the isEmpty() function. You should also change int maxSize = 10 to int maxSize= 11 and make the necessary change in the pop() function as well as this is where the error is occurring. Finally, make sure to change the value in your stack initialization from 10 to 11. I've changed your code and it should now work properly! Enjoy!
public class Stack {
private int[] stackArray; // Stack array of objects
private int maxSize = 11; // Max size of the stack
private int top; // top integer of stack
public Stack(int maxSize) {
stackArray = new int[maxSize];
top = -1;
}
public boolean isEmpty() {
return (top == -1); // true if stack is empty
}
public boolean isFull() {
return (top == maxSize); // true if full
}
public int size() {
return (top-1); // Return the # of items
}
public void push(int item) // put element into array
{
if (!isFull()) {
top++;
stackArray[top] = item;
}
}
public Object pop() {
if (!isEmpty()) {
return stackArray[top--];
} else
throw new IllegalStateException("Stack empty");
}
public Object peek() {
return stackArray[top+1];
}
public String toString() {
return "Size: " + maxSize + " Capcaity: " + top; // complete: show the size and capacity
}

Related

index 0 out of bounds

I have just started Java.I have some C++ experience.I want to implement a stack class.Here is my class:
public class stack {
private static int MAX;
stack(int a)
{
MAX = a;//input max size of stack
}
stack()
{
MAX = 1000;//default max size stack is 1000
}
private int[] my_stack = new int[MAX];
private int top = 0;
public void push(int x)
{
if (this.top > MAX)System.out.println("OVERFLOW");
else my_stack[this.top++] = x;//ERROR LINE
}
public void pop()
{
if (this.top == 0)System.out.println("TOO LOW");
else this.top--;
}
public int top()
{
return my_stack[this.top - 1];
}
}
The error says:
Index 0 out of bounds for length 0
at stack.push(stack.java:17)
at MainClass.main(MainClass.java:7)
Can anyone explain me the problem?
Here some minimal changes, explained with comments
public class stack {
private int max; //Removed static here and changed to lowercase, this is an instance field
stack(int a)
{
max = a; //input max size of stack
my_stack = new int[max]; //Here the value of max is initialized an you can use it
}
stack()
{
this(1000); //Call other constructor, just to avoid duplicate code
}
private int[] my_stack; //You can't initialize the array there, since you don't know the size yet
private int top = 0;
public void push(int x)
{
if (this.top >= max)System.out.println("OVERFLOW"); //You must check with >=, not just > since the maximum index is max-1
else my_stack[this.top++] = x;//ERROR LINE
}
public void pop()
{
if (this.top == 0)System.out.println("TOO LOW");
else this.top--;
}
public int top()
{
return my_stack[this.top - 1];
}
}

Printing a stack with a "for" loop

I am trying to print the elements of stack S in reverse (using a "for" loop), but so far I haven't had any success.
I have managed to do it with "pop" fairly easily, but the second way evades me. My solution for "pop" is commented out at the end of the code.
Any help will be appreciated.
PS. Most of this code is irrelevant to the question, but if I knew what and where I can cut out, I probably wouldn't need help at all. Sorry.
package simplearraystackofchars;
public class SimpleArrayStackofchars implements Stack {
protected int capacity; // The actual capacity of the stack array
public static final int CAPACITY = 2; // default array capacity
protected Object S[], K[]; // Generic array used to implement the stack
protected int top = -1; // index for the top of the stack (-1 = empty stack)
public SimpleArrayStackofchars() {
this(CAPACITY); // default capacity
}
public SimpleArrayStackofchars(int cap) {
capacity = cap;
S = new Object[capacity];
}
public int size() {
return (top + 1);
}
public boolean isEmpty() {
return (top == -1);
}
public void push(Object element) throws FullStackException {
if (size() == capacity) {
//throw new FullStackException("Stack is full. Stack size max is "+ capacity);
// can replace previous line with code to double stack size
doubleArray();
}
S[++top] = element;
}
public Object top() throws EmptyStackException {
if (isEmpty()) {
throw new EmptyStackException("Stack is empty.");
}
return S[top];
}
public Object pop() throws EmptyStackException {
Object element;
if (isEmpty()) {
throw new EmptyStackException("Stack is empty.");
}
element = S[top];
S[top--] = null; // dereference S[top] for garbage collection.
return element;
}
private void doubleArray() {
Object[] newArray;
System.out.println("Stack is full (max size was " + capacity + "). Increasing to " + (2 * capacity));
//double variable capacity
capacity = 2 * capacity;
newArray = new Object[capacity];
for (int i = 0; i < S.length; i++) {
newArray[i] = S[i];
}
S = newArray;
}
public static void main(String[] args) {
Stack S = new SimpleArrayStackofchars();
S.push("1");
S.push("2");
S.push("3");
S.push("4");
S.push("5");
S.push("6");
// Stack K is created by popping elements of Stack S from the top.
// This reverses the order.
//
// Stack K = new SimpleArrayStackofchars();
// while (!S.isEmpty()) {
// K.push(S.pop());
// }
// while (!K.isEmpty()) {
// System.out.println(K.pop());
// }
while (!S.isEmpty()) {
System.out.println(S.pop());
}
}
}
Not really sure about what you need that for loop for, but this should produce the same result:
Stack K = new SimpleArrayStackofchars();
for (int i = 0, i < S.size(); i++) {
K.push(S.pop());
}
for (int i = 0, i < K.size(); i++) {
System.out.println(K.pop());
}

CircularArrayQueue implementation Java

I am trying to implement a CircularArrayQueue. I've been given a JUnit test which my queue must pass.I suppose I am doing something wrong with the front and rear pointers. How should i approach learning data structures and algorithms ?
import java.util.NoSuchElementException;
public class CircularArrayQueue implements MyQueue {
private Integer[] array;
// initial size of the array
private int N;
private int front;
private int rear;
public CircularArrayQueue() {
this.N = 10;
array = new Integer[N];
front = rear = 0;
}
public CircularArrayQueue(int size) {
this.N = size;
array = new Integer[N];
front = rear = 0;
}
// enqueues an element at the rear of the queue
// if the queue is already full it is resized, doubling its size
#Override
public void enqueue(int in) {
if (rear == N) {
if (front == 0) {
resize();
array[rear] = in;
rear++;
} else {
array[rear] = in;
rear = 0;
}
} else {
array[rear] = in;
rear++;
}
}
public void resize() {
Integer[] temp = new Integer[array.length * 2];
for (int i = 0; i < array.length; i++) {
temp[i] = array[i];
}
temp = array;
}
// dequeues an element
// if the queue is empty a NoSuchElement Exception is thrown
#Override
public int dequeue() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The queue is full");
}
int headElement = array[front];
if (front == N) {
array[front] = null;
front = 0;
} else {
array[front] = null;
front++;
}
return headElement;
}
#Override
public int noItems() {
return N - getCapacityLeft();
}
#Override
public boolean isEmpty() {
return (getCapacityLeft() == N);
}
// return the number of indexes that are empty
public int getCapacityLeft() {
return (N - rear + front) % N;
}
}
Your initialization is absolutely fine, and we do start with:
front = rear = 0;
Befor adding an item to the Q, we modify rear as
rear = (rear + 1) % N;
The % allows us to maintain the circular property of the queue. Also you must be wondering that if we modify rear before adding any item, then 0 index is left empty, well we have to compromise here with one array item being left blank, in order to have correct implementations for checking of isEmpty() and isFull() functions:
That said, the correct code for isEmpty() is:
#Override
public boolean isEmpty()
{
return front == rear;
}
You should also have a function isFull() like:
#Override
public boolean isFull()
{
return front == ((rear + 1) % N);
}
Also the line temp = array; in your resize() should be array = temp; and you must also update the value of N after calling resize().
Hence, the correct code is:
import java.util.NoSuchElementException;
public class CircularArrayQueue implements MyQueue
{
private Integer[] array;
//initial size of the array
private int N;
private int front;
private int rear;
private int count = 0;//total number of items currently in queue.
public CircularArrayQueue()
{
this.N = 10;
array = new Integer[N];
front = rear = 0;
}
public CircularArrayQueue(int size)
{
this.N = size;
array = new Integer[N];
front = rear = 0;
}
//enqueues an element at the rear of the queue
// if the queue is already full it is resized, doubling its size
#Override
public void enqueue(int in)
{
count++;
if (isFull())
{
resize();
rear = (rear + 1) % N;
array[rear] = in;
}
else
{
rear = (rear + 1) % N;
array[rear] = in;
}
}
public void resize()
{
Integer[] temp = new Integer[array.length*2];
N = array.length*2;
for(int i=0; i<array.length; i++)
{
temp[i] = array[i];
}
array = temp;
}
//dequeues an element
// if the queue is empty a NoSuchElement Exception is thrown
#Override
public int dequeue() throws NoSuchElementException
{
if(isEmpty())
{
throw new Exception("The queue is empty");
}
front = (front + 1) % N;
int headElement = array[front];
count--;
return headElement;
}
#Override
public int noItems()
{
return count;
}
#Override
public boolean isEmpty()
{
return front == rear;
}
#Override
public boolean isFull()
{
return front == ((rear + 1) % N);
}
//return the number of indexes that are empty
public int getCapacityLeft()
{
return N - 1 - count;
}
}

using Java Loop for ArrayList to print each time

I have a method which I basically want to simulate first filling the queue and then after that removing the first person and adding a new person each time in my public void mySimulation() method:
import java.util.*;
public class People {
private final int DEFAULT_CAPACITY = 100;
private int front, rear, count;
private ArrayList<thePeople> people;
private int theMaxCapacity;
//-----------------------------------------------------------------
// Creates an empty queue using the specified capacity.
//-----------------------------------------------------------------
public People(int initialCapacity) {
front = rear = count = 0;
people = new ArrayList<thePeople>(Collections.nCopies(5, (thePeople) null));
}
//-----------------------------------------------------------------
// Adds the specified element to the rear of the queue, expanding
// the capacity of the queue array if necessary.
//-----------------------------------------------------------------
public void enque(thePeople element) {
if (this.isFull()) {
System.out.println("Queue Full");
System.exit(1);
} else {
people.set(rear, element);
rear = rear + 1;
if (rear == people.size()) {
rear = 0;
}
count++;
}
}
//-----------------------------------------------------------------
// Removes the element at the front of the queue and returns a
// reference to it. Throws an EmptyCollectionException if the
// queue is empty.
//-----------------------------------------------------------------
public thePeople dequeue() {
if (isEmpty()) {
System.out.println("Empty Queue");
}
thePeople result = people.get(front);
people.set(front, null);
front = (front + 1) % people.size();
count--;
return result;
}
//-----------------------------------------------------------------
// Returns true if this queue is empty and false otherwise.
//-----------------------------------------------------------------
public boolean isEmpty() {
return (count == 0);
}
//-----------------------------------------------------------------
// Returns the number of elements currently in this queue.
//-----------------------------------------------------------------
public int size() {
return count;
}
public boolean isFull() {
return count == people.size();
}
public void mySimulation() {
Random rand1 = new Random();
thePeople theM = null;
if (this.isFull()) {
this.people.remove(0);
System.out.println("Enqueueing...");
this.enque(people.get(rand1.nextInt(people.size())));
thePeople r1 = people.get(rear - 1);
System.out.println(people.toString());
System.out.println(r1);
for (int e = 0; e < people.size(); e++) {
if (people.get(e) instanceof thePeople) {
System.out.println("G");
} else {
System.out.println("D");
}
}
}
}
//-----------------------------------------------------------------
// Returns a string representation of this queue.
//-----------------------------------------------------------------
#Override
public String toString() {
String result = "";
int scan = 0;
while (scan < count) {
if (people.get(scan) != null) {
result += people.get(scan).toString() + "\n";
}
scan++;
}
return result;
}
public static void main(String[] args) {
People Q1 = new People(25);
thePeople call1 = new thePeople("John King", "001 456 789");
thePeople call2 = new thePeople("Michael Fish", "789 654 321");
Q1.enque(call1);
Q1.enque(call2);
System.out.println(Q1.toString());
ArrayList<thePeople> callerDetails = new ArrayList<>(Arrays.asList(call1, call2));
Random rand = new Random();
for (int z = 0; z <= 4; z++) {
Q1.enque(callerDetails.get(rand.nextInt(callerDetails.size())));
}
System.out.println(Q1.toString());
}
}
any suggestions on how I could repeat this process such that I will first check that the queue is full,
if so remove the first item and add a new person to it using my arrayList each time i my my public void mySimulation() method: as I cant get my head round this at the moment?
Your code is filled with errors:
First make sure you remove the "the" you accidently placed before people in many lines of your code .
Then adjust some of your methods to the right parameters and return types.
As for you question:
it is simple
public void MySimulation(){
if(Queue.isFull()){
Queue.dequeue;}
Queue.enqueue;}

How can I implement a Dynamic Array Stack in Java?

I need to modify a class to create a dynamic array stack.
My code at this point looks something like this:
public class DynamicArrayStack<E> implements Stack<E> {
private E[] elems; //used to store the elements
public static final int defaultIncrement = 25;
private final int increment;
private int top;
#SuppressWarnings( "unchecked" )
public DynamicArrayStack( int increment ) {
this.increment = increment;
elems = (E[]) new Object[ increment ];
top = 0;
}
/**
* Constructor with no parameter that will initialize
* the stack to have an array whose size is the value
* of increment and memorise that value as the value
* of increment.
*/
public void ArraySize() { }
public boolean isEmpty() {
return top == 0;
}
public E peek() {
return elems[ top-1 ];
}
public E pop() {
// save the top element
E saved = elems[ --top ];
// scrub the memory, then decrements top
elems[ top ] = null;
return saved;
}
public void push( E elem ) {
// stores the element at position top, then increments top
elems[ top++ ] = elem;
}
public String toString() {
StringBuffer b;
b = new StringBuffer( "DynamicArrayStack: {" );
for ( int i=top-1; i>=0; i-- ) {
if ( i!=top-1 ) {
b.append( "," );
}
b.append( elems[ i ] );
}
b.append( "}" );
return b.toString();
}
}
How do I edit the first constructor to set increment as the initial size of the stack and that same value to be used when increasing or decreasing the size of the array. My method for doing this seems way too simple. Parameter must be > 0 and a fixed number of cells are added or removed when the size of the array changes.
The second constructor should set the stack to have an array whose size is the value of increment. I keep getting errors here because I can't figure out how to do that because I thought that was already set in the first constructor. Also the size of the array as the value of increment.
Also how do I make this class capable of changing the capacity of the stack and into which method should I place that code?
Here is the simple java code to implement it:
1)Stack based:
public class DynamicArrayStack {
public static void main(String[] args) {
DynamicStack dstack=new DynamicStack(2);
System.out.println("--Pushing--");
dstack.push(1);
dstack.push(2);
dstack.display();
dstack.push(3);
dstack.push(2);
dstack.push(5);
dstack.display();
System.out.println("--Popping--");
dstack.pop();
dstack.pop();
dstack.pop();
dstack.display();
}
}
class DynamicStack {
private int top;
private int capacity;
private int[] array;
public DynamicStack(int cap) {
capacity = cap;
array = new int[capacity];
top = -1;
}
public void push(int data) {
if (isFull()){
expandArray(); //if array is full then increase its capacity
}
array[++top] = data; //insert the data
}
public void expandArray() {
int curr_size = top + 1;
int[] new_array = new int[curr_size * 2];
for(int i=0;i<curr_size;i++){
new_array[i] = array[i];
}
array = new_array; //refer to the new array
capacity = new_array.length;
}
public boolean isFull() {
if (capacity == top+1)
return true;
else
return false;
}
public int pop() {
if (isEmpty()) {
System.out.println("Stack is empty");
return -1;
} else {
reduceSize(); //function to check if size can be reduced
return array[top--];
}
}
public void reduceSize() {
int curr_length = top+1;
if (curr_length < capacity / 2) {
int[] new_array = new int[capacity / 2];
System.arraycopy(array, 0, new_array, 0, new_array.length);
array = new_array;
capacity = new_array.length;
}
}
public boolean isEmpty() {
if (top == -1)
return true;
else
return false;
}
public void display() {
for (int i = 0; i <= top; i++) {
System.out.print(array[i] + "=>");
}
System.out.println();
System.out.println("ARRAY SIZE:" + array.length);
}
}
OUTPUT:
--Pushing--
1=>2=>
ARRAY SIZE:2
1=>2=>3=>2=>5=>
ARRAY SIZE:8
--Popping--
1=>2=>
ARRAY SIZE:4
2)Link List based:
public class LinkListStack {
public static void main(String[] args) {
StackList stack = new StackList();
System.out.println("--Pushing--");
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.push(6);
stack.display();
System.out.println("--Popping--");
stack.pop();
stack.pop();
stack.display();
}
}
class Node {
private int data;
private Node next;
public Node(int d) {
data = d;
next = null;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
class StackList {
private Node top;
private int length;
public StackList() {
length = 0;
top = null;
}
public void push(int data) {
Node temp = new Node(data);
if (top == null) {
top = temp;
} else {
temp.setNext(top);
top = temp;
}
length++;
}
public int pop() {
Node temp=top;
int data = top.getData();
top = top.getNext();
temp=null;
length--;
return data;
}
public void display() {
Node temp = top;
if (isEmpty()) {
System.out.println("Stack is empty");
} else {
while (temp != null) {
System.out.print(temp.getData() + "=>");
temp = temp.getNext();
}
}
System.out.println();
}
public boolean isEmpty() {
return (top == null);
}
}
OUTPUT:
--Pushing--
6=>5=>4=>3=>2=>1=>
--Popping--
4=>3=>2=>1=>
Default constructor
Your default constructor could simply call your other constructor with a default increment value. For example:
public DynamicArrayStack() {
this(defaultIncrement);
}
Expanding the array
The correct place to expand the array is within the push method. When attempting to add a new element you can check if the array is large enough, and if not create a new larger array. For example you could do the following:
#Override
public E push(final E elem) {
// Check if we need to expand the array
if (elems.length - 1 == top) {
#SuppressWarnings("unchecked")
final E[] newElems = (E[]) new Object[elems.length + increment];
System.arraycopy(elems, 0, newElems, 0, elems.length);
elems = newElems;
}
// stores the element at position top, then increments top
elems[top++] = elem;
return elem;
}
If you want to shrink the array the sensible place to do this would be in the pop() method. You might want to consider only reducing the length when (top + (increment*2))<elems.length to avoid repeatedly copying arrays when you're on the boundary.

Categories

Resources