Main.java
/**
* Author : Berk Soysal
*/
package herrberk;
import java.util.Scanner;
import java.util.Stack;
public class Main {
// Scanner objects to read information from the console
private static final Scanner intsc = new Scanner(System.in);
private static final Scanner strsc = new Scanner(System.in);
// Shows the pushed element to the stack and the stack itself after the push
private static void showPush(Stack st, int b) {
st.push(new Integer(b));
System.out.println("Push "+ b + " to the stack");
System.out.println("stack: " + st);
}
// Shows the popped element from the stack
private static void showPop(Stack st){
Integer a = (Integer) st.pop();
System.out.println("Removed "+ a + " from the stack");
System.out.println("stack: " + st);
}
// Main function
public static void main(String[] args) {
int a, i=3;//number of elements desired (stack capacity)
Stack st = new Stack ();
System.out.println("Stack is empty!");
// Loop to push integers
while (i-- > 0){
System.out.println("Enter an integer: ");
a = intsc.nextInt();
showPush(st, a);
}
// User enters 0 to empty the stack
System.out.println("Press Enter 0 to empty the stack");
String ss = strsc.nextLine();
if(ss.contentEquals("0")){
while (!st.empty()){
showPop(st);
}
}
else {
System.out.println("Stack remains full !");
System.exit(1);
}
}
}
Output:
Stack is empty!
Enter an integer:
953
Push 953 to the stack
stack: [953]
Enter an integer:
442
Push 442 to the stack
stack: [953, 442]
Enter an integer:
555
Push 555 to the stack
stack: [953, 442, 555]
Press Enter 0 to empty the stack
0
Removed 555 from the stack
stack: [953, 442]
Removed 442 from the stack
stack: [953]
Removed 953 from the stack
stack: []
Please leave a comment if you have any questions, comments or suggestions. Thanks..
Disqus Comments Loading..