Question

Write a program that uses a stack to reverse its inputs. Your stack must be generic...

Write a program that uses a stack to reverse its inputs. Your stack must be generic and you must demonstrate that it accepts both String and Integer types. Your stack must implement the following methods:

push,

pop,

isEmpty (returns true if the stack is empty and false otherwise), and

size (returns an integer value for the number of items in the stack).

You may use either an ArrayList or a LinkedList to implement your stack. Also, your pop method must throw an IndexOutOfBoundsException if the user attempts to “pop” something off an empty stack. Name your stack class “Stack” and put it in a file named Stack.java.

Create a StackTest.java file to demonstrate all of the methods of your stack. Instantiate two stacks; one for String and one for Integer. Push words/integers onto your stack. After you have pushed a series of words/integers on your stack use a while loop to pop and print each item. If your stack is working properly your inputs should print in reverse order. Be sure that you calls to pop are in a try statement and will catch the IndexOutOfBoundsException, if thrown.

Note: Java has a Stack class, but you may not use it. You must create your own Stack class and your class must have the following operations (all of which must be demonstrated): push, pop, isEmpty, and size.

Here is an example screen shot of a working stack that reverses words and integers:

Write a program that uses a stack to reverse its i

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

// Stack.java

import java.util.ArrayList;

public class Stack<T> {

      //underlying data structure

      private ArrayList<T> stk;

     

      //default constructor

      public Stack() {

            //initializing array list

            stk = new ArrayList<T>();

      }

     

      //adds an element to the top

      public void push(T item) {

            //simply adding

            stk.add(item);

      }

     

      //removes and returns an element from top

      public T pop() {

            if (stk.isEmpty()) {

                  //stack is empty, throwing exception

                  throw new IndexOutOfBoundsException("Cannot pop from empty Stack!");

            }

            //removing and returning last element

            return stk.remove(stk.size()-1);

      }

     

      //returns true if stack is empty

      public boolean isEmpty() {

            return stk.isEmpty();

      }

     

      //returns the current size of stack

      public int size() {

            return stk.size();

      }

}

// StackTest.java

public class StackTest {

      public static void main(String[] args) {

            //creating a String stack

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

            //creating a String

            String str = "The rain in Spain";

            System.out.println("Pushing on to the stack: \"" + str + "\"");

            //splitting str by white space, looping through each string

            for (String word : str.split(" ")) {

                  //adding to string stack

                  stringStack.push(word);

            }

            System.out.println("The size of the String stack is "

                        + stringStack.size());

            System.out.println("Stack is empty? " + stringStack.isEmpty());

            System.out.println("Popping elements off the stack");

            //looping and popping each element from stack, displaying it

            while (!stringStack.isEmpty()) {

                  try {

                        System.out.print(stringStack.pop() + " ");

                  } catch (IndexOutOfBoundsException ex) {

                        System.out.println(ex.getMessage());

                  }

            }

            System.out.println("\nStack is empty? " + stringStack.isEmpty());

            System.out.println("The size of the String stack is "

                        + stringStack.size());

            System.out.println("\n\n");

            //creating an integer stack

            Stack<Integer> intStack = new Stack<Integer>();

            //creating a String containing some integers

            str = "1 2 3 4 5";

            System.out.println("Pushing on to the Integer stack: \"" + str + "\"");

            //splitting str by white space, looping through each string

            for (String number : str.split(" ")) {

                  //converting current string to integer, adding to integer stack

                  intStack.push(Integer.parseInt(number));

            }

            System.out.println("The size of the Integer stack is "

                        + intStack.size());

            System.out.println("Stack is empty? " + intStack.isEmpty());

            System.out.println("Popping elements off the stack");

            //looping and popping each element from stack, displaying it

            while (!intStack.isEmpty()) {

                  try {

                        System.out.print(intStack.pop() + " ");

                  } catch (IndexOutOfBoundsException ex) {

                        System.out.println(ex.getMessage());

                  }

            }

            System.out.println("\nStack is empty? " + intStack.isEmpty());

            System.out.println("The size of the Integer stack is "

                        + intStack.size());

      }

}

/*OUTPUT*/

Pushing on to the stack: "The rain in Spain"

The size of the String stack is 4

Stack is empty? false

Popping elements off the stack

Spain in rain The

Stack is empty? true

The size of the String stack is 0

Pushing on to the Integer stack: "1 2 3 4 5"

The size of the Integer stack is 5

Stack is empty? false

Popping elements off the stack

5 4 3 2 1

Stack is empty? true

The size of the Integer stack is 0


answered by: ANURANJAN SARSAM
Add a comment
Know the answer?
Add Answer to:
Write a program that uses a stack to reverse its inputs. Your stack must be generic...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Use Java to implement a basic stack using an array of integers. For the stack, you...

    Use Java to implement a basic stack using an array of integers. For the stack, you will create an array of integers that holds 5 numbers. To make it easier, you can declare the array at the class level. That way you will be able to use the array in any method in your class without using parameters. Your input/output interface should look something like the following: What operation do you want to do? push What number do you want...

  • java create java program that make stack with LinkedList and stack is implement iterator. When stack’s iterator call next(), it pop its data. here is the example of output //by user 5 1 2 3 4 5 //then...

    java create java program that make stack with LinkedList and stack is implement iterator. When stack’s iterator call next(), it pop its data. here is the example of output //by user 5 1 2 3 4 5 //then output comes like this 5 4 3 2 1 Stack is empty. here is the code that i'm going to use class Stack<T> implements Iterator<T> {    LinkedList<T> list;       public Stack() {        list = new LinkedList<T>();    }       public boolean isEmpty() {        return list.isEmpty();   ...

  • » Part A: Stack Create a Stack struct that is a wrapper for your linked list o You should impleme...

    Using C Please comment » Part A: Stack Create a Stack struct that is a wrapper for your linked list o You should implement the following functions that take a stack o void push(Stack * stack, int value) ● int pop(Stack * stack) Prompt the user to input 5 integers, and use the stack to reverse the integers Print the result to the screen. o o » Part B: Queue o Create a Queue struct that is a wrapper for...

  • C++ Create an array-based implementation of a stack. Each element of the stack should store a...

    C++ Create an array-based implementation of a stack. Each element of the stack should store a string. The stack class should include 3 private member variables (maximum stack size, top of the stack index, and a pointer to the array that holds the stack elements). Public member methods should include a constructor (with an argument of stack maximum size that is used to create a dynamic array), a destructor (that deletes the dynamic array), a push method (argument is a...

  • JAVA, please You must write a robust program meaning that your program should not crash with...

    JAVA, please You must write a robust program meaning that your program should not crash with any given data. Data validation must be done any time that user enters an input. Write a program that 1. Gets an infix expression form the user and evaluate the expression using stack ADT a. Finds the postfix equivalent of the given infix expression b. Evaluate the created postfix expression. c. Note: your program should not crash when you enter an invalid expression such...

  • Dynamic Implementation of Stack - The purpose is to use our dynamic implementation of stack. The...

    Dynamic Implementation of Stack - The purpose is to use our dynamic implementation of stack. The application will be to add large numbers. Review adding large numbers Remember that we can use stacks to safely add integer values that overflow the int data type g. in Java, the maximum possible int value Integer.MAX_VALUE is: 2147483647 so any int addition larger than this will overflow and fail Using stacks to add large numbers safely Will actually represent the large integers to...

  • Create a C++ program. Include comment, input and output file. STACK IMPLEMENTATION USING AN link list IMPLEMENT THE FOLLOWING STACK OPERATIONS using  a TEMPLATED CLASS. WRITE ALL THE FULL-FUNCTION DE...

    Create a C++ program. Include comment, input and output file. STACK IMPLEMENTATION USING AN link list IMPLEMENT THE FOLLOWING STACK OPERATIONS using  a TEMPLATED CLASS. WRITE ALL THE FULL-FUNCTION DEFINITIONS NEEDED for the OPERATIONS. OUTPUT: PRINT ALL THE ELEMENTS ON THE STACK. Stack Operations initializestack: Initializes the stack to an empty state. isEmptyStack: Determines whether the stack is empty. If the stack is empty, it returns the value true; otherwise, it returns the value false. isFul1stack: Determines whether the stack...

  • JAVA QUESTION 2.One use of a Stack is to reverse the order of input. Write a...

    JAVA QUESTION 2.One use of a Stack is to reverse the order of input. Write a complete method that reads a series of Strings from the user. The user enters "end" to stop inputting words. Then, output the Strings in reverse order of how they were entered. Do not output the String “end”. Use a stack to accomplish this task. Invoke only the methods push, pop, peek, and isEmpty on the stack object. Here is an example of how the...

  • I need to implement a stack array but the top of the stack has to be...

    I need to implement a stack array but the top of the stack has to be Initialize as the index of the last location in the array.    //Array implementation of stacks.    import java.util.Arrays;       public class ArrayStack implements Stack {        //Declare a class constant called DEFAULT_STACK_SIZE with the value 10.           private static final int DEFAULT_STACK_SIZE = 10;           /* Declare two instance variables:            1. An integer called...

  • I need to implement raw array Stack for create empty stack, isEmpty, isFull, push, pop, and...

    I need to implement raw array Stack for create empty stack, isEmpty, isFull, push, pop, and size using below pseudo code. I need two classes with stack pseudo code implementation and the main method to demonstrate the correct working of each operation. pseudo code StackADT (using raw array) class StackADT { int top int items[] int max StackADT(int n) Initialize array to n capacity top = 0 max = n boolean isEmpty() if array has no elements return true else...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT