Write the code for a small function called myStack which cre

Write the code for a small function called myStack, which creates a Stack object of String elements, named cities. Add \"Sydney\", then \"London\", then \"New York\" and then \"Beijing\" to cities. Then print each element on the screen, one per line. Print each element in a way that causes cities to be empty (i.e. have 0 elements) afterwards. (6 mks)

Solution

PROGRAM CODE:

package stack;

import java.util.Stack;

public class MyStackClass {

   //stack function

   public static void myStack()

   {

       //creating a stack object called cities

       Stack<String> cities = new Stack<String>();

      

       //Adding cities into the stack

       cities.push(\"Sydney\");

       cities.push(\"London\");

       cities.push(\"New York\");

       cities.push(\"Beijing\");

      

       //using while loop to loop through the stack till its empty

       while(!cities.isEmpty())

       {

           // pop function is used to remove elements from the stack

           // pop() returns the elemets which is printed on the csreen

           System.out.println(cities.pop());

       }

   }

  

   // Main function for the class

   public static void main(String args[])

   {

       myStack(); // function call to the stack method

   }

}

OUTPUT:

Beijing

New York

London

Sydney

Write the code for a small function called myStack, which creates a Stack object of String elements, named cities. Add \
Write the code for a small function called myStack, which creates a Stack object of String elements, named cities. Add \

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site