JAVA - How do you push a string into a stack? - java

I have an assignment to push Strings into a stack. I created a program that will store numbers but I cannot figure out the correct way to define the array to take a string. Here is my code. My Java is rusty so I am trying to remember all this from my first java class 2 years ago. I am sure it is super simple but I cannot find anything online where strings are stored in a stack for me to see how to do it. Thanks for the help!
public class stackx {
private int maxSize; //number of items in stack
private int[] stackArray;
private int top; // top of stack
public stackx(int arraySize) {
maxSize = arraySize;
stackArray = new int[maxSize];
top = -1;
}
public void push(int a) { //put value on top of stack
if (top == maxSize - 1)
{
System.out.println("Stack is full");
} else {
top = top + 1;
stackArray[top] = a;
}
}
public int pop() { //take item from top of stack
if (!isEmpty())
return stackArray[top--]; // access item, decrement top
else {
System.out.println("Stack is Empty");
}
}
public int peek() //peek at the top of the stack
{
return stackArray[top];
}
public boolean isEmpty() { //true if stack is empty
return top == -1;
}
public void display() {
for (int i = 0; i <= top; i++) {
System.out.print(stackArray[i] + " ");
}
System.out.println();
}
} // End class stackx
**Driver class Here**
public class practicestack {
public static void main(String[] args) {
stackx newStack = new stackx(5);
newStack.push(redShirt);
newStack.push(greenShirt);
newStack.push(yellowPants);
newStack.push(purpleSocks);
newStack.push(pinkSocks);
stackx.peek();
//Display the Full Stack
newStack.display();
//Test removing a value using pop method
newStack.pop();
newStack.display();
}
}

This should be easy, I will provide you a small hint, if you still can't figure it out, I will post entire code
when you declare something like this
private int[] stackArray;
and use this array to push and pop your items, as this is Integer array you can only use this implementation for Integers.
Now your requirement is to push and pop Strings, so essentially you should do something like this.
private String[] stackArray;
Note : Your Push and pop method will change likewise, those will be small changes
Hope this helps!
Good luck.

Your stack only takes ints. You need it to take Objects if you want to store anything at all. Java doesn't let you manipulate pointers, so you can't just use int like in C/C++. You could also use generics, e.g. public class stackx<T>, which would give you something like stackx<String> newStack = new stackx<>(5);.

Just modify int to String.Here is the Demo.

Related

Does assigning an object to another mean that instant variables will aslo change?

I am trying to to create a stacks which has the following API:
Stacks(int n)// creates stacks of size n
pop() //returns the last element pushed in the stacks
pop(int n) //returns an array of of n elements
push(int e) //appends an element to the stacks
push(int n, ar[]) //appends an array to the stack
The stacks should be able to dynamically change size when needed, so client programs dont have to do it every time.
I have done all that only my problem is when assigning object A to object B doesn't that mean that A will now points to the address of B?
Here is my code and i hope it explaines what i mean
public class Stacks {
/*
* constructs a stack object
* #param n that will determine that size of the stacks to be constructed
*/
public Stacks(int n)
{
this.elemetns= new int[n];
this.size=n;
this.top=-1;
}
/*
* constructs a stack object, with size of 2 when no parameter is given
*/
public Stacks()
{
this.elemetns= new int[2];
this.size=2;
this.top=-1;
}
public int pop()
{
if (top<0)
{
System.out.println("Error code 2: Empty stacks");
return -1;
}
else
{
int n= this.elemetns[top];
top--;
return n;
}
}
public int [] pop(int size)
{
if (this.size<size)
{
System.out.println("Error code 3: The Maximum number of elements that can be acquired is "+ this.size);
return null;
}
else
{
int res[]= new int[size];
for (int i=0;i<size;i++)
{
res[i]=pop();
}
return res;
}
}
public void push(int e)
{
if (!isFull())
{
this.elemetns[++top]=e;
System.out.println(e+" has been pushed to the stack ");
}
else
{
updateStacksSize(this);
this.elemetns[++top]=e;
System.out.println(e+" has been pushed to the stack ");
}
}
public void push(int n,int [] ar)
{
for (int i=0;i<n;i++)
this.push(ar[i]);
}
private void updateStacksSize(Stacks s)
{
int newSize= s.top*2;
Stacks newStacks= new Stacks(newSize);
for (int i = s.top; i>-1;i--)
newStacks.elemetns[i]=s.pop();
s= newStacks;//shouldnt newStacks get garbage collected
//and s gets the new address and attributes of newStacks?
}
private boolean isFull(){return this.size==(this.top+1);}
public static void main(String[] args)
{
Stacks s= new Stacks(5);
for (int i=0;i<7;i++)
s.push(i+1);
System.out.println();
int []arr= s.pop(6);
for (int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
private int elemetns[];
private int top;
private int size;
}
Why does running this program results in problem with the old size although the current object's has been updated.
one more question is it possible to assign this= newStacks instead of instantiating new Stacks object
In Java you assign object references to variables.
I have done all that only my problem is when assigning object A to object B doesn't that mean that A will now points to the address of B?
s= newStacks;//shouldnt newStacks get garbage collected
//and s gets the new address and attributes of newStacks?
It is the other way around since the assignment in Java is from right to left.
"I have done all that only my problem is when assigning object A to object B doesn't that mean that A will now points to the address of B?"
if this is what you meant then:
Stacks A = new Stacks();
Stacks B = A;
Then what this means is that B is now pointing to A.
You're kinda over do it. A stack should consist of a chain of nodes, like an singel-linked list of nodes. I've written an example on this below, see if you can see how it works.
public class Stack <E> {
private StackItem<E> currTop;
private int size;
private int max;
private static class StackItem<E> {
private E e;
private StackItem<E> next;
}
public Stack(int max) {
currTop = null;
size = 0;
this.max = max;
}
public void add(E e){
if ((size+1) == max) throw new StackOverflowError("Max items in stack is reached");
StackItem<E> old = currTop;
currTop = new StackItem<>();
currTop.e = e;
currTop.next = old;
size++;
}
public E getFirst() {
if (currTop == null) return null;
E output = currTop.e;
currTop = currTop.next;
size --;
return output;
}
public E showFirst() {
return currTop.e;
}
public int getSize() {
return size;
}
}

Stack using stack in java

I have a problem with my homework. And I need all the help that you can give me.
i need to create a combination of a stack that can store any type of data and a Stack that works with elements of type Stack. I´m very confused.
The methods that I was supposed to implement were:
initializeStack()
isEmpty()
isFull()
Push()
Pop()
showStack()
countElements()
And this is what i have so far:
public class pilita {
Object vectorPila[];
int tope;
public pilita(int tam){
vectorPila=new Object[tam];
tope=-1;
}
public void inicializarPila(){
tope=-1;
}
public void push(Object dato){
tope++;
vectorPila[tope]=dato;
}
public Object pop(){
Object fuera=vectorPila[tope];
tope--;
return fuera;
}
public boolean pilaVacia(){
return tope==-1;
}
public boolean pilaLlena(){
return vectorPila.length-1==tope;
}
public Object cima(){
return vectorPila[tope];
}
public Object contar(){
return tope+1;
} }
All the methods are well implemented (Using my logic).
But how can i make an Stack using Stack data type using those methods?.
I would be very grateful if anyone could help me.
Also here is the original problem.
Stack of little Stacks: The elements of the Data Structure Little Stack are of any type of data. The elements of the Data Structure Stack are of Stack type.
// Java code for stack implementation
import java.io.*;
import java.util.*;
class Test
{
// Pushing element on the top of the stack
static void stack_push(Stack<Integer> stack)
{
for(int i = 0; i < 5; i++)
{
stack.push(i);
}
}
// Popping element from the top of the stack
static void stack_pop(Stack<Integer> stack)
{
System.out.println("Pop :");
for(int i = 0; i < 5; i++)
{
Integer y = (Integer) stack.pop();
System.out.println(y);
}
}
// Displaying element on the top of the stack
static void stack_peek(Stack<Integer> stack)
{
Integer element = (Integer) stack.peek();
System.out.println("Element on stack top : " + element);
}
// Searching element in the stack
static void stack_search(Stack<Integer> stack, int element)
{
Integer pos = (Integer) stack.search(element);
if(pos == -1)
System.out.println("Element not found");
else
System.out.println("Element is found at position " + pos);
}
public static void main (String[] args)
{
Stack<Integer> stack = new Stack<Integer>();
stack_push(stack);
stack_pop(stack);
stack_push(stack);
stack_peek(stack);
stack_search(stack, 2);
stack_search(stack, 6);
}
}
In Java, they are called Collections and the are analogous to the standard template library(STL) of C++.Now, what you can do is define a void type stack and typecast it for various type of elements.
In c, stack.h has the following stack structure
typedef struct{
void *elems;
int elemSize;
int allocLength;
int logLength;
void (*freefnc)(void *);
} Stack;
void stackNew(Stack *s, int elemSize, void (*freefnc)(void *));
void stackDispose(Stack *s);
void stackPush(Stack *s, void *elemAddr);
void stackPop(Stack *s, void *target);
You can study more about them here:-
http://www.geeksforgeeks.org/java/ (see collections in java)
http://www.geeksforgeeks.org/c-plus-plus/#STL (see standard template library(STL))
for defining void type generics in java refer:-
What's the difference between Void and no parameter?
https://coderanch.com/t/450693/java/pass-void-generic-parameter-type

printing stack without popping elements java

for a task I have to write a method which prints the stack, that part is easy
public void print(stack s)
{
while(!isEmpty())
{
System.out.println(s.peek());
s.pop();
}
}
The problem is that after I printed the stack, my task is to print the bottom element on the stack, which isn't there any more cause I used s.pop() in my print method. This is my code for printing the bottom element.
public void bottom(stack s)
{
if(isEmpty())
{
System.out.println("Stack is empty");
}
else
{
System.out.println(stackArray[0]);
}
}
My question is: How should i modifie the print method so I don't have to pop the elements from the stack? Or is there another way to make it so that the stack still holds my elements after using print method?
as resquested this is the stack we're using in our classes(most of it is in dutch):
public class MyStack
{
protected Object[ ] stackArray;
protected int top;
private int grootte;
private static final int DEFAULT_GROOTTE = 10;
public MyStack( )
{
grootte = DEFAULT_GROOTTE;
stackArray = new Object[grootte];
top = 0;
}
public boolean isEmpty( )
{
if (top == 0)
return true;
else
return false;
}
public void push(Object e)
{
if (top == grootte)
allocateMore( );
stackArray[top] = e;
top++;
}
public Object pop( )
{
if(isEmpty( ))
{
System.out.println("Stack leeg : er kan geen element van de stack afgehaald worden.");
return null;
}
top--;
return stackArray[top];
}
public Object peek( )
{
if(isEmpty( ))
{
System.out.println("Stack leeg : er kan geen topelement van de stack getoond worden.");
return null;
}
return stackArray[top-1];
}
public int size( )
{
return top;
}
private void allocateMore( )
{
Object[ ] original = stackArray;
grootte = grootte * 2;
stackArray = new Object[ grootte];
for(int i = 0; i < grootte/2; i++)
{
stackArray[i] = original[i];
}
}
}
since my rep isn't high enough to answer my own question a quick edit
I think I've found an other way to print the stack using this
public void print(stack s)
{
for(int i =top-1; i>=0;i--)
System.out.println(stackArray[i]);
}
it probably isn't the best way to do it, but it's working :P
If you use the built-in java.util.Stack type, then this derives from Vector, so you can use getElement(int) to read elements at any stack depth.
If this is your own code, you will have to add a method to do the same.
Alternatively, you can pop the elements into another stack or a List type and then rebuild the stack after printing but that would be very inefficient and your teacher will most probably frown about such a solution.
There is a simple workaround if you just want to see the contents without any fancy stuff.
System.out.println(Arrays.toString(myStack.toArray()));
if (!_stack.empty())
Check whether the Stack is Empty
for(int i=_stack.size()-1; i>=0;i--)
System.out.println(_stack.get(i));
getting stack values
Use Iterator to loop through the Stack, as they work on any Collection object.

Java Stack with elements limit

I know this question has asked many times but after seaching for an hour i still have problem.
I want to use a lifo stack which has a max number of elements it can store.After it reach the max number is deletes the element at first place and replace it with the new so in first pop i can get this element and in second i have to get the element at size-1.
What i tried:
1) Using a modified Stack ,as described here .The problem is that it always returning the first 5 elements(if the size is 5) i added.
class StackSizable<E> extends Stack<E>{
int maxSize;
StackSizable(int size)
{
super();
this.maxSize=size;
}
#Override
public E push(E elt) {
super.push(elt);
while (this.size() > this.maxSize) {
this.removeElementAt(this.size() - 1);
}
return null;
}
}
2)Using an ArrayDeque ,i dont see any diference from a simple Stack , its not setting any limit(am i using it wrong?)
ArrayDeque<State> lifo = new ArrayDeque<State>(5);
lifo.pop();
lifo.push(state);
I want to use this in a puzzle game for undo-redo functionality
Solved: I ended using a fixed size stack as tom said ,mainly for the performance
public class FixedStack<T> {
private T[] stack;
private int size;
private int top;
private int popBalance = 0;//its used to see if all the elements have been popped
public FixedStack(T[] stack) {
this.stack = stack;
this.top = 0;
this.size = stack.length;
}
public void push(T obj) {
if (top == stack.length)top = 0;
stack[top] = obj;
top++;
if (popBalance < size - 1)popBalance++;
}
public T pop() {
if (top - 1 < 0)top = size;
top--;
T ob = stack[top];
popBalance--;
return ob;
}
public void clear() {
top = 0;
}
public int size() {
return size;
}
public boolean poppedAll() {
if (popBalance == -1)return true;
return false;
}
}
I think the most efficient way to this is with a fixed array, with size equal to your max # of elements, and an index that points to the element that is currently the 'top' of the queue.
When you add a new element you add it at index+1 (wrapping back to element 0 if necessary) and possibly overwriting an element that no longer fits. When you pop an element you do the reverse.
This way your data structure never has to be re-ordered, and you can use an array which is more light-weight then a collection.
When the maximum size has been reached, your line
this.removeElementAt(this.size() - 1);
then immediately removes the last pushed element (which you just pushed), which is the top of the stack. You need to remove the first element instead (bottom of the stack):
this.removeElementAt(0);

Trying to implement Array Stack in Java but Push is not working

I've been working for a couple of hours now trying to get an Stack based on an Array built and implemented. I have checked several sources and it looks like my ArrayStack class is constructed properly. However, when I run debug, 'head' stays null and size & sp go back to 0: therefore, nothing is actually getting pushed on the stack. Can someone help me understand what I have implemented incorrectly?
Here is my ArrayStack class:
public class ArrayStack <T>{
protected int sp; //empty stack
protected T[] head; //array
private int size;
#SuppressWarnings("unchecked")
public void stack(T t){
sp = -1;
size = 24; //sets the default size of the stack
head = (T[]) new Object [size];
}
public boolean isFull(){
return sp == -1;
}
public void push (T t){
if (!isFull())
head[++sp] = t;
}
public T pop (){
if (isFull()){
return null;
}
else
return head[sp--]; //LINE 30
}
}
Here is my Main Method:
public class StacksAndQsMain {
public static void main(String[] args) {
//Array Implementation
ArrayStack<String> as = new ArrayStack<String>();
String s = "Hello";
String s1 = "World";
String s2 = "Again";
as.push(s);
as.push(s1);
as.push(s2);
System.out.println (as.pop()); //LINE 15
System.out.println();
System.out.println (as.pop());
System.out.println();
System.out.println (as.pop());
System.out.println();
}
}
Lastly, here is my stack trace:
Exception in thread "main" java.lang.NullPointerException
at stackAndQs.ArrayStack.pop(ArrayStack.java:30)
at stackAndQs.StacksAndQsMain.main(StacksAndQsMain.java:15)
My variables at public void push (T t)
this ArrayStack<T> (id=17)
head null
size 0
sp 0
t "Hello" (id=18)
You are using the default constructor for the class, which will initialize all of the data members to their default values:
public class ArrayStack <T>{
protected int sp; //empty stack <-- initialized to 0
protected T[] head; //array <-- initialized to null
private int size; // <-- initialized to 0
// ... snip
}
You need to implement the default constructor to initialize this object state to the defaults you want (in the stack() method). When you call push, the isFull method will return false (as the default integer value of 0 != -1).
Instead of implementing a default constructor, you could just call stack() before using it, but there's no reason to let your object be constructed in a booby-trapped state!
Additionally, your isFull method should be checking sp against the size variable, right now it is behaving as an isEmpty check :-)
I noticed two things.
First as others have mentioned you needed to create a constructor and initialize the array. Second, the isFull method should check that sp != this.size -1, basically making sure your not at the 24 element limit of your stack implementation. After changing, isFull you should negate the if conditional in the push method to check that the stack is not full. Also, I would remove the check on the pop method to check if the stack isFull, why prevent someone from popping an element just because the stack is full? Instead check that the stack is not empty.
public class ArrayStack<T> {
protected int sp; // empty stack
protected T[] head; // array
private int size;
#SuppressWarnings("unchecked")
public ArrayStack() {
sp = -1;
size = 24; // sets the default size of the stack
head = (T[]) new Object[size];
}
public boolean isFull() {
return sp == this.size -1;
}
public boolean isEmpty() {
return sp == -1;
}
public void push(T t) {
if (!isFull())
head[++sp] = t;
}
public T pop() {
if (isEmpty()) {
return null;
} else
return head[sp--]; // LINE 30
}
public static void main(String[] args) {
// Array Implementation
ArrayStack<String> as = new ArrayStack<String>();
String s = "Hello";
String s1 = "World";
String s2 = "Again";
as.push(s);
as.push(s1);
as.push(s2);
System.out.println(as.pop()); // LINE 15
System.out.println();
System.out.println(as.pop());
System.out.println();
System.out.println(as.pop());
System.out.println();
}
}
You're not using any selfdefined constructor. You're using the default one which causes your sp variable to be '0' instead of '-1'. This results in an sp value of 3 after your pushing, but sp[3] has no data in it which results in a NPE when you're trying to pop it.
Change your stack method to
public ArrayStack(T t){
sp = -1;
size = 24; //sets the default size of the stack
head = (T[]) new Object [size];
}
to make it a selfdefined constructor.
After you push "Hello" (1st object) sp becomes 0 and head[0] is assigned. From this moment all further "pushes" will produce nothing since your IsFull is still testing (sp == -1).

Categories