In: Computer Science
Can you fix my code and remove the errors? Thank you!! ^^
//////////////////////////////////////////////////////////////////////////////////////////////////////
public class StackException<T, size> extends Throwable { private final T[] S = null ; public StackException(String s) { } public T top() throws StackException { if (isEmpty()) throw new StackException("Stack is empty."); int top = 0; return S[top]; } private boolean isEmpty() { return false; } public T pop() throws StackException { T item; if (isEmpty()) throw new StackException("Stack underflow."); int top = 0; item = S[top]; S[top--] = null; return item; } public void push(T item) throws StackException { if (<Object capacity = null; size() == capacity >)throw new StackException("Stack overflow."); int top = 0; S[++top] = item; } private void size() { } }
Hey, I have changed the class name because generic exception class can't be created. I have used array of Object because we can't create array of generic.
Java code:
// stack exception class which print error msg
class StackException extends Throwable {
StackException(String s) {
System.out.println(s);
}
}
// Generic class Stack
// we can't create generic exception class
// that's why i have changed the name of the class
public class Stack<T> {
private Object[] S = null;
private int capacity;
private int top ;
public Stack() {
this.S = new Object[10];
this.capacity = 10;
this.top = -1;
}
public Stack(int cap) {
this.S = new Object[cap];
this.capacity = cap;
this.top = -1;
}
@SuppressWarnings("unchecked")
public T top() throws StackException {
if (isEmpty()) throw new StackException("Stack is
empty.");
return (T)S[top];
}
private boolean isEmpty() {
if (size() == 0 )
return true ;
return false;
}
@SuppressWarnings("unchecked")
public T pop() throws StackException {
T item;
if (isEmpty()) throw new StackException("Stack
underflow.");
item = (T)S[top];
S[top--] = null;
return item;
}
public void push(T item) throws StackException {
if (size() == capacity)throw new StackException("Stack
overflow.");
S[++top] = item;
}
private int size() {
return top + 1;
}
}
I have tested this code and it's working fine.
Hope you like it
Any Query? Comment Down!
I have written for you, Please up vote the answer as it encourage us to serve you Best !