the main: package StackPractice;
public class MainIntStack {
public static void main(String[] args) {
// TODO Auto-generated method stub
IntStack stackno1 = new IntStack();
// why get error?: The field IntStack.top is not visible
// System.out.println(stackno1.top);
if (!stackno1.isFull()) {
stackno1.push(1);
stackno1.push(2);
}
if (!stackno1.isEmpty()) {
// stackno1.pop();
// stackno1.pop();
System.out.println(stackno1.pop());
} else {
System.out.println("stack is empty");
}
}
}
The methods:
package StackPractice;
public class IntStack { private int[] stack; private int top; private int size;
// instructor to set default values // ca we have two constructor of the same method? public IntStack() { top = -1; size = 50; // stack = new int[50];
}
public IntStack(int size) {
top = -1;
this.size = size;
//
stack = new int[this.size];
}
//check if pushing value work properly thats why it is boolean public boolean push(int item) { if (!isFull()) { top++; stack[top] = item; return true; } else { return false; }
}
public boolean isFull() {
// checks if top is equal to stack.length-1
return (top == stack.length - 1);
}
public int pop() {
if (!isEmpty())
return stack[top--];
else {
return top;
//why print can not be done?
//System.out.println("The stack is already empty");
}
}
public boolean isEmpty() {
// if (top <= 0) {
// return true;
// } else {
// return false;
return (top==-1);
}
}