0 Members and 1 Guest are viewing this topic.
/** * This is a working stack example for beginners that wanted to know * the logic of stack.. * * @author J.P.Hernandez * @version 1.0 */import java.util.Scanner;public class stack { public static void main(String args[]){ Scanner scan = new Scanner(System.in); int stackSize; int choice; int current=-1; int pushItem; System.out.println("We will create a stack!"); System.out.println("First let us determine the Stack Type and Size"); System.out.print("Integer is the type of Stack, and the size is: "); stackSize = scan.nextInt(); int stackArray[] = new int[stackSize]; System.out.println("Now that the stack size is "+ stackSize+", let us begin!"); System.out.println("\n"); do{ System.out.println("1. Push"); System.out.println("2. Pop"); System.out.println("3. Top"); System.out.println("4. Exit"); System.out.print("I want to: "); choice = scan.nextInt(); //this is if choice is to push if(choice==1){ current++; if(current==stackSize){ System.out.println("STACK IS FULL"); current--; }else{ System.out.println("Push Me: "); pushItem = scan.nextInt(); stackArray[current] = pushItem; System.out.println(pushItem+" is pushed into stackArray"); } } //this is if choice is to pop if(choice==2){ if(current==-1){ System.out.println("STACK IS EMPTY"); }else{ current--; System.out.println("Popped: "+stackArray[++current]); current--; } } //this is if choice is to show top if(choice==3){ if(current==-1){ System.out.println("NO TOP"); }else{ System.out.println("TOP: "+stackArray[current]); } } //this is if choice is to exit the program if(choice==4){ System.out.println("Thank you for learning stacks..."); } }while(choice!=4); }}