All pastes #927054 Raw Edit

Anonymous

public java v1 · immutable
·published 2008-03-04 00:24 UTC
rendered paste body
/* * Assignment #6: Reverse Stack * Develop software to reverse the elements in a stack.   * Print the stack before and after reversing the elements. *  * Accepts a string (word), pushing the characters to * a stack while priting it out, then analyzes the stack * in reverse to determine if the word is an anagram */package org.lurey.cs2b.assignments;import java.util.Stack;import java.util.Scanner;/** * Assignment for reversing java.util.Stack * @author Matan Lurey */public class ReverseStack {    /**     * Program entry point     * @param args the command line arguments     */    public static void main(String[] args) {        // Create a new stack object        Stack<Character> stack = new Stack<Character>();        print("Stack (java.util.Stack) constructed...");                // Get a word        print("Input a word: ");        String word = new Scanner(System.in).nextLine();        print("Word inputted = " + word + "\nAdding to the stack...");                // Input to the stack        for (int i=0, l=word.length(); i<l; ++i)            stack.push(word.charAt(i));               print(stack);                // Return a reversed stack        print("Reversing stack...");        Stack reversed = reverse(stack);        print(reversed);                // Compare the two stacks        print("Comparing both stacks for an anagram...");                if (stack.equals(reversed))            print("Yes, it is an anagram!");        else            print("No, it is not an anagram!");                print("Program complete...");    }        /**     * Shorthand for printing a message out     * @param message     */    public static void print(String message) {        System.out.println(message);    }        /**     * Prints all the elements of the stack     * @param stack     */    public static void print(Stack stack) {        print("Printing stack [" + stack + "]...");                for (int i=0, l=stack.size(); i<l; ++i)            print("Stack #" + i + "\t\t" + stack.get(i));    }        /**     * Reverses the elements in the stack and returns it     * @param stack     */    public static Stack reverse(Stack stack) {        Stack buffer = new Stack();        Stack temp = (Stack) stack.clone();                while (!temp.isEmpty())            buffer.push(temp.pop());               return buffer;    }}