In: Computer Science
create a stack class based on an array of type double of fixed size. In the class,
The array should have the default size of 5.
The array size should be settable via a constructor.
The following methods must be implemented:
push – inserts a value a the top of the stack
pop – returns the top value, removing it from the stack
isEmpty – returns true if the stack is empty, false otherwise
isFull - – returns true if the stack is full, false otherwise
Please notice you must use an array not an arraylist or any other list. Im having trouble with a couple parts of it. Thanks
Also use java
class Stack {
private int size;
private double[] data;
/**
*
*/
public Stack() {
data = new double[5];
size = 0;
}
/**
* @param maxSize
*/
public Stack(int maxSize) {
data = new double[maxSize];
size = 0;
}
/**
*
*/
public void display() {
for (int i = 0; i < size; i++) {
System.out.print(data[i] + ", ");
}
System.out.println();
}
/**
* inserts a value a the top of the stack
*
* @param value
*/
public void push(double value) {
if (size >= data.length)
throw new
RuntimeException("Stack full");
data[size] = value;
size++;
}
/**
* returns the top value, removing it from the
stack
*
* @return
*/
public double pop() {
if (isEmpty())
throw new
RuntimeException("Stack empty");
size--;
return data[size];
}
/**
* returns true if the stack is empty, false
otherwise
*
* @return
*/
public boolean isEmpty() {
return size == 0;
}
/**
* returns true if the stack is full, false
otherwise
*
* @return
*/
public boolean isFull() {
return size == data.length;
}
/**
* @param args
*/
public static void main(String[] args) {
Stack stack = new Stack();
// displaying output
stack.push(8.3);
stack.push(6.3);
stack.push(4.3);
stack.push(2.3);
stack.push(4.1);
System.out.println("FINAL STACK
CONTENT ");
stack.display();
System.out.println("pop from
stack-->" + stack.pop());
System.out.println("check stack is
empty-->" + stack.isEmpty());
stack.push(9.1);
System.out.println("check stack is
full-->" + stack.isFull());
System.out.println(" ");
}
}
OUTPUT:
FINAL STACK CONTENT
8.3, 6.3, 4.3, 2.3, 4.1,
pop from stack-->4.1
check stack is empty-->false
check stack is full-->true