Hey need some help please! I\'ve made this stack class and for some reason i hav
ID: 3764604 • Letter: H
Question
Hey need some help please! I've made this stack class and for some reason i have errors under all my fullStackException's.
I was hoping someone could fix it or point me in the right direction. THANKS!!!
import java.util.EmptyStackException;
public class Stack<E> {
private final int size; // max # of elements
private int top; // location of the top element
private E[] elements; // stack elements
Stack <Integer> intStack=new Stack<Integer>(5);
public void push(Integer pushValue) {
int x=0;
if (top == size - 1)
x++;
}
public Stack(int s) {
size = (s > 0 ? s : 10);
top = -1; // stack initially empty
elements = (E[]) new Object[size];
}
public void push(E pushValue) {
if (top == size - 1)
throw new FullStackException();
elements[++top] = pushValue;
}
public E pop() {
if (top == -1)
throw new EmptyStackException();
return elements[top];
}
public <T> void testPush(Stack<T> stack, T [ ] elements){
try{
for(T element : elements){
System.out.printf("%s ", element);
stack.push(element);
}
}catch(FullStackException exp){
fullStackException.printStackTrace();
System.out.println();
}
}
}
Explanation / Answer
Please find the modified solution:
import java.util.EmptyStackException;
public class Stack<E> {
private final int size; // max # of elements
private int top; // location of the top element
private E[] elements; // stack elements
Stack<Integer> intStack = new Stack<Integer>(10);
public void push(Integer pushValue) {
int x = 0;
if (top == size - 1)
x++;
top=x;
}
public Stack(int s) {
size = (s > 0 ? s : 10);
top = -1; // stack initially empty
elements = (E[]) new Object[size];
}
public void push(E pushValue) throws FullStackException {
if (top == size - 1)
throw new FullStackException();
elements[++top] = pushValue;
}
public E pop() {
if (top == -1)
throw new EmptyStackException();
return elements[top];
}
public <T> void testPush(Stack<T> stack, T[] elements) {
try {
for (T element : elements) {
System.out.printf("%s ", element);
stack.push(element);
}
} catch (FullStackException exp) {
exp.printStackTrace();
System.out.println();
}
}
public static void main(String[] args) {
String[] elements = { "raghu", "rams","sandeep","pradeep","rakesh" };
Stack<String> stack = new Stack<String>(5);
stack.testPush(stack, elements);
}
}
class FullStackException extends Exception {
FullStackException() {
super("Stack is Full");
}
}