Receive input from user to add elements into a Stack list using Java:
import java.util.Scanner; import java.util.Stack; public class Inherit { public static void main(String[] args) { Scanner scan = new Scanner(System.in); Stack stack = new Stack(); // Very similar to C++ :) String s = ""; while(!s.equalsIgnoreCase("end")){ System.out.print("Enter a word to procced or enter the end to exit program:: "); s = scan.next(); if(!s.equalsIgnoreCase("end")){ stack.push(s); } } System.out.println("Reverse order: "); while (!stack.isEmpty()) { String word = stack.peek(); System.out.println(word); stack.pop(); } } }
Bye-Bye 🙂
Leave a Reply