// Decode.java from Lewis and Loftus, page 508, modified to // demonstrate user-defined stack implemeted as an array. import java.io.*; // Each node of a Stack object contains a Character data and a // reference to the next node. Initially, the stack is defined // by a reference to the "top" node. class Stack { int maxsize; private Character[] word; int top; public Stack () { maxsize = 100; // assume default size of 100 characters word = new Character [maxsize]; top = -1; } public boolean empty () { return (top == -1); } public boolean full () { return (top == maxsize - 1); } public void push (Character letter) { top++; word[top] = letter; } public Character pop () { Character l = word[top]; top--; return l; } public String toString () { String result = ""; int index = 0; while (index < word.length) { result += word[index].toString(); index++; } return result; } } public class MyDecode2 { public static void main (String[] args) throws IOException { BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in)); Stack word = new Stack(); String message; int index = 0; System.out.println ("Enter the coded message:"); message = stdin.readLine(); System.out.println ("The decoded message is:"); while (index < message.length()) { while (index < message.length() && message.charAt(index) != ' ') { word.push (new Character(message.charAt(index))); index++; } // Print current word in reverse order while (!word.empty()) System.out.print (((Character)word.pop()).charValue()); System.out.print (" "); index++; } System.out.println(); } }