Search code examples
javastringstack

Turn stack into a string?


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);
    
    }

}

Solution

  • 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;