Click here to Skip to main content
15,885,309 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Create a program that will allow the user to select a stack operation such as insert, pop, peek, display and to re-run the program or to exit as outputted below:

What I have tried:

public static void main(String[] args) {
   
   Scanner sc = new Scanner(System.in);
   System.out.println("Enter the maximum size of the stack:");
   int stackSize = sc.nextInt();
   

   System.out.println("1. Insert an element 2. Pop an element 3. Peek of the stack 4. Display the elements of the stack");
   int answer1 = sc.nextInt();
   
   if (answer1 == 1){
       System.out.println("Please enter the element to insert: ");
       Stack <Integer> stack = new Stack<Integer>();
       for(int i= 0; i>stackSize; i++){
       int answer2 = sc.nextInt(i);
       
       System.out.println("Want to continue? y or n ");
       char answer3 = sc.next().charAt(0);    
      }
      
   }else{
       if(answer1 == 2){
           Stack.pop();
           
       }
   }
        
    
}
Posted
Updated 26-Oct-22 6:17am
v2

1 solution

If i is equal to zero then it cannot be greater than stackSize. Unless the user enters a negative number.
Java
for(int i= 0; i>stackSize; i++){
int answer2 = sc.nextInt(i);

Change the for statement to:
Java
for(int i= 0; i < stackSize; i++){
int answer2 = sc.nextInt(i);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900