I'm trying to create a stack for characters in java but there's a bug which doesn't push the characters into stack. I input a String and extract each character to place in Stack. Weirdly, the stack only stores one character of string. Can someone help me out?
int top, capacity;
char[] stack;
stack7() {
top = -1;
capacity = 6;
stack = new char[capacity];
}
public boolean isempty() {
return top == -1;
}
public boolean isfull() {
return top == capacity - 1;
}
public void push(char data) {
if (isfull()) {
System.out.println("Stack is full");
} else {
stack[++top] = data;
}
}
public char pop() {
if (isempty()) {
System.out.println("Stack is empty");
}
return stack[top--];
}
public char peek() {
return stack[top];
}
public void display() {
int temp = top;
if (temp >= 0) {
System.out.print(stack[temp] + " ");
temp--;
}
System.out.println();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("enter string");
String str = sc.nextLine();
stack7 st = new stack7();
for (int i = 0; i < str.length(); i++) {
st.push(str.charAt(i));
}
st.display();
}