2.
Develop a stack class to hold a maximum of 10 integers with
suitable methods. Develop a JAVA main
method to illustrate Stack operations.
import [Link];
class Stack {
private int[] elements;
private int top;
public Stack() {
elements = new int[10];
top = -1;
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == 9;
}
public void push(int element) {
if (isFull()) {
[Link]("Stack is full. Cannot push more
elements.");
} else {
elements[++top] = element;
[Link]("Pushed: " + element);
}
}
public void pop() {
if (isEmpty()) {
[Link]("Stack is empty. Cannot pop
elements.");
} else {
int poppedElement = elements[top--];
[Link]("Popped: " + poppedElement);
}
}
public void printStack() {
if (isEmpty()) {
[Link]("Stack is empty.");
} else {
[Link]("Stack: ");
for (int i = 0; i <= top; i++) {
[Link](elements[i] + " ");
}
[Link]();
}
}
}
public class Main {
public static void main(String[] args) {
Stack stack = new Stack();
while(true)
{
[Link]("Stack Operations");
[Link]("1. Push");
[Link]("2. Pop");
[Link]("3. Display");
[Link]("4. Exit");
Scanner scanner = new Scanner([Link]);
[Link]("Enter your Choice: ");
int choice = [Link]();
switch(choice)
{
case 1: [Link]("Enter Number to push: ");
int num = [Link]();
[Link](num);
break;
case 2:
[Link]();
break;
case 3: [Link]();
break;
case 4: [Link](0);
break;
default: [Link]("Invalid choice ");
}
}
}
}