1

I'm working on a project for class and we need to create a method that takes the stack we created and when called print itself out as a string. This is what I have so far; the method is at the bottom called toString();.

package edy.bsu.cs121.stack;

import javax.swing.JOptionPane;

public class myArrayStack<T> {

    private final int DEFAULT_CAPACITY = 100;
    private int top;
    private T[] stack;

    @SuppressWarnings("unchecked")
    public myArrayStack(){

        top = 0;
        stack = (T[])(new Object[DEFAULT_CAPACITY]);
    
    }

    @SuppressWarnings("unchecked")
    public myArrayStack(int initialCapacity){
     
        top = 0;
        stack = (T[])(new Object[initialCapacity]);
            
    }

    public void myPush(String first){
    
        stack[top] = (T) first;
        top++;
    }

    public T myPop(){
    
        if (isEmpty()){
            JOptionPane.showMessageDialog(null, "Stack is empty!");
        } else {
            top--;
        }
        T result = stack[top];
        stack[top] = null;
        return result;
    }

    public T myPeek(){
        if (isEmpty()){
            JOptionPane.showMessageDialog(null, "Stack is empty!");
        }
        return stack[top-1];
    }

    public boolean isEmpty(){
    
        if (top == 0){
            return true;    
        }
    
        return false;
    }

    public int mySize(){
        return top;
    }

    //Searches for a name

    public int mySearch (T element) {
    {   
        int spot = -1;
        for(int i = 0; i< top; i ++){
            if(element.equals(stack[i])){
                spot = i;
            } 
        }
        return spot;
    }
    }

    public String toString(){
        int i=top;
    
        do {
            T result = stack[top-i];
            i--;
            return (String) result;
        } while (i>=0);
    
    }

}
2
  • the toString method will only return the top item in the Stack; the loop won't run through the whole stack like I need it to. Commented Jun 24, 2013 at 2:45
  • You pop each element out your stack and call to string. Read more about to string in tutorialspoint.com/java/number_tostring.htm Commented Jun 24, 2013 at 2:51

5 Answers 5

2

Using Stream API:

Stack<Character> st = new Stack<>();
st.add('a');st.add('b');st.add('c');

String stStr = st.stream().map(s -> s.toString()).collect(Collectors.joining(""));

System.out.println(stStr);
Sign up to request clarification or add additional context in comments.

Comments

0

Calling return in a loop will immediately exit the loop. What you need to do is something like this:

String message = ""; //a string to store the whole message
for (int c = stack.length - 1; c >= 0; c--) {
  message += ", "+stack[c];  //add the next element to the message
}
message = message.substring(2); //cut off the first ", "
return message;

Comments

0

Use a StringBuilder to handle the toString creation. A template you could use is

public String toString(){
    StringBuilder output = new StringBuilder();
    output.append(this.getClass().getName());
    output.append("[");
    // append fields

    // to append the Stack you could use Arrays.toString
    // or just iterate as you are trying to do
    int i=top;

    do {
        T result = stack[top-i];
        i--;
        output.append(result != null?result.toString():"null");
    } while (i>=0);

    output.append("]");
    return output.toString();
}

Comments

0

The intuitive way is to use a combination of Stream API + StringBuilder.

Stream API + StringBuilder

StringBuilder sb = new StringBuilder("");
stack.stream().forEach(c -> sb.append(c)); // iterates from bottom to top of stack
System.out.println(sb.toString());

Comments

0

Java 11+. ArrayDeque. Stream API.

public static void main(String[] args) {
    System.out.println(execute("azxxzy"));
}

public static String execute(String s) {
    Deque<Character> stack = new ArrayDeque<>();
    for (Character c : s.toCharArray()) {
        stack.addLast(c);
    }

    return stack.stream().map(Object::toString).collect(Collectors.joining());
}

output: azxxzy

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.