Question

Given main() complete the Stack class by writing the methods push() and pop(). The stack uses...

Given main() complete the Stack class by writing the methods push() and pop(). The stack uses an array of size 5 to store elements. The command Push followed by a positive number pushes the number onto the stack. The command Pop pops the top element from the stack. Entering -1 exits the program.

Ex. If the input is

Push 1
Push 2
Push 3
Push 4
Push 5
Pop
-1

the output is

Stack contents (top to bottom):
1

Stack contents (top to bottom):
2
1

Stack contents (top to bottom):
3
2
1

Stack contents (top to bottom):
4
3
2
1

Stack contents (top to bottom):
5
4
3
2
1

Stack contents (top to bottom):
4
3
2
1

File is marked as read only

Current file:

PushPopStack.java

import java.util.Scanner;

public class PushPopStack {

public static void main (String[] args) {
Scanner scnr = new Scanner(System.in);
Stack stack = new Stack(5);
String action; // Push or Pop   
int numInput; // Integer value to push

action = scnr.next();

while (!action.equals("-1")) {
if (action.equals("Push")) {
numInput = scnr.nextInt();
stack.push(numInput);
System.out.println("Stack contents (top to bottom):");
stack.printStack();
}
else if (action.equals("Pop")) {
stack.pop();
System.out.println("Stack contents (top to bottom):");
stack.printStack();
}

action = scnr.next();
}
}
}

Current file:

Stack.java

public class Stack {
  
private int topElement;
int size;
int [] array;

public Stack(int arraySize) {
size = arraySize;
array = new int[size];
topElement = -1;
}

// TODO: Write a method to push a value into the stack


// TODO: Write a method to pop the top value from the stack   


public void printStack() {
int i;
  
for(i = topElement; i >= 0; --i) {
System.out.println(array[i]);
}
System.out.println();
}
}

Homework Answers

Answer #1
public class Stack {

    private int topElement;
    int size;
    int[] array;

    public Stack(int arraySize) {
        size = arraySize;
        array = new int[size];
        topElement = -1;
    }

    public void push(int num) {
        if (topElement < size - 1)
            array[++topElement] = num;
    }

    public int pop() {
        if (topElement == -1) return -1;
        return array[topElement--];
    }

    public void printStack() {
        int i;

        for (i = topElement; i >= 0; --i) {
            System.out.println(array[i]);
        }
        System.out.println();
    }
}
Know the answer?
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
Similar Questions
Create a class StacktwoPopArr using Arrays, Change the pop function so that two elements get popped...
Create a class StacktwoPopArr using Arrays, Change the pop function so that two elements get popped everytime instead of the one. If there is only one element in the stack, just pop the one element and report that the stack is now empty. If stack is empty, it should just report that stack is empty. All other functions for StackArray remain the same. using java StackArray.java: public class StackArray {       private final int size = 20; //Size of...
ex3 Write a method public static boolean isPalindrome(String input) that uses one or more stacks to...
ex3 Write a method public static boolean isPalindrome(String input) that uses one or more stacks to determine if a given string is a palindrome. [A palindrome is a string that reads the same forwards and backwards, for example ‘racecar’, ‘civic’]. Make sure that your method works correctly for special cases, if any. What is the big-O complexity of your method in terms of the list size n. Supplementary Exercise for Programming (Coding) [Stacks] Download and unpack (unzip) the file Stacks.rar....
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {       ...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {        Stack<Integer> new_stack = new Stack<>();/* Start with the empty stack */        Scanner scan = new Scanner(System.in);        int num;        for (int i=0; i<10; i++){//Read values            num = scan.nextInt();            new_stack.push(num);        }        int new_k = scan.nextInt(); System.out.println(""+smallerK(new_stack, new_k));    }     public static int smallerK(Stack s, int k) {       ...
class Car{ private String make; public Car(String make){ this.make = make; } public String toString(){ return...
class Car{ private String make; public Car(String make){ this.make = make; } public String toString(){ return make; } } class Node<T>{ public T data; public Node next; public Node(T data){ this.data = data; this.next = null; } } public class StackLinkedList<T>{ //Single field of type Node    //to represent the front of the stack //operation push() /* The push operation is equivalent to the inserting a node at the head of the list. */ public void push(T data){ } //operation...
Complete the // TODO sections in the EasyRental class. Create a method that implements an iterative...
Complete the // TODO sections in the EasyRental class. Create a method that implements an iterative sort that sorts the vehicle rentals by color in ascending order (smallest to largest) Create a method to binary search for a vehicle based on a color, that should return the index where the vehicle was found or -1 You are comparing Strings in an object not integers. Ex. If the input is: brown red white blue black -1 the output is: Enter the...
Complete the following C program to solve the parenthesis matching problem using a stack. We studied...
Complete the following C program to solve the parenthesis matching problem using a stack. We studied the problem and the algorithm in class. Given a sequence of chars (symbols), check if each “(”, “{”, or “[” is paired with a matching “)”, “}”, or “[”. For example, correct: ( )(( )){([( )])}     correct: (( )(( ))){([( )])}   incorrect: )(( )){([( )])}     incorrect: ({[ ])}     incorrect: (   #include <stdio.h> #include <stdlib.h> #define size 100 void push(char *s, int* top, char element);...
Instructions: SLLStack (12 pts) ● Using the two properties below, implement the stack interface using the...
Instructions: SLLStack (12 pts) ● Using the two properties below, implement the stack interface using the SLLNode class from Lab 2: ○ top_node → SLLNode object or None ○ size → int, keep track of stack size ● Implement the push( ), pop( ), top( ) methods ● Use SLLNode methods: get_item( ), set_item( ), get_next( ), set_next( ) ● (5 pts) In push(item): ○ Create new SLLNode with item ○ Add new node before top node ○ Update top_node...
Consider a generic Stack class implemented using linked list with the following methods: public boolean isEmpty(),...
Consider a generic Stack class implemented using linked list with the following methods: public boolean isEmpty(), which returns true if and only if the stack is empty; public T pop() throws StackUnderflowException, which removes and returns the top element of the stack (if the stack is empty, it throws StackUnderflowException); public T peek() throws StackUnderflowException, which returns the top element of the stack (but does not remove it; it throws exception if stack is empty); public void push(T element), which...
Suppose that a client performs an intermixed sequence of Stack push and pop operations. The push...
Suppose that a client performs an intermixed sequence of Stack push and pop operations. The push operations put the integers 0 through 9 in order onto the Stack. That is, the following operations must appear in this order with any number of pop operations in between: push(0), push(1), …, push(8), push(9). Each pop operation pops the top item off the Stack and prints the return value. Determine if each of the following sequences can or cannot be a result of...
import java.util.Scanner; public class FindMinLength { public static int minLength(String[] array) { int minLength = array[0].length();...
import java.util.Scanner; public class FindMinLength { public static int minLength(String[] array) { int minLength = array[0].length(); for (int i = 0; i < array.length; i++) { if (array[i].length() < minLength) minLength = array[i].length(); } return minLength; } public static void main(String[] args) { Scanner in = new Scanner(System.in); String[] strings = new String[50]; for (int i = 0; i < strings.length; i++) { System.out.print("Enter string " + (i + 1) + ": "); strings[i] = in.nextLine(); } System.out.println("Length of smallest...