In Java, Define a class Stack implementing the idea of a stack of integers. Your
ID: 638215 • Letter: I
Question
In Java,
Define a class Stack implementing the idea of a stack of integers. Your class should have the following methods:
void push(int n)
int pop()
boolean isEmpty()
You can assume that your stack will never be expected to store more than 100 items at a time.
I would suggest using an array to hold the items in the stack and have a variable to keep track of how many items are currently in the stack. So you will want something like
int[] items = new int[100];
int size = 0;
Then, to push an item you store the new item in items[size] and then add one to size. To pop an item, you subtract one from size and return items[size].
You should also define some sort of print method in the Stack class to print out the current contents of the stack. Then you can test your class with a short test program which creates a new Stack and then pushes two numbers, then prints the stack, then pops one, prints, etc.
PART TWO (3 pts)
Use a stack to write a program which reads in a bunch of numbers and then prints them in reverse order. The end of the input should be indicated by a value of 9999. Your program will use a Scanner to read numbers and then push each number into a Stack. When the input is done, your program will pop numbers from the stack and print them until the stack is empty.
Explanation / Answer
part A)
part B)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.