【问题标题】:JAVA - How do you push a string into a stack?JAVA - 你如何将字符串推入堆栈?
【发布时间】:2017-06-02 03:32:40
【问题描述】:

我有一个将字符串压入堆栈的任务。我创建了一个存储数字的程序,但我无法找出定义数组以获取字符串的正确方法。这是我的代码。我的 Java 生锈了,所以我试图从 2 年前我的第一个 Java 课程中记住这一切。我确信它非常简单,但是我在网上找不到任何将字符串存储在堆栈中的东西,让我看看如何去做。感谢您的帮助!

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

【问题讨论】:

标签: java string stack push


【解决方案1】:

这应该很容易,我会给你一个小提示,如果你仍然无法弄清楚,我会发布整个代码 当你声明这样的事情时

private int[] stackArray;

并使用此数组来推送和弹出您的项目,因为这是整数数组,您只能将此实现用于整数。

现在你的要求是推送和弹出字符串,所以基本上你应该做这样的事情。

private String[] stackArray;

注意:你的 Push 和 pop 方法也会发生变化,这些都是很小的变化

希望这会有所帮助!

祝你好运。

【讨论】:

  • 谢谢!这行得通。我尝试了几次,但一定是遗漏了其他东西。我删除了我的整个代码并重写了它然后它工作了:)
【解决方案2】:

你的堆栈只需要ints。如果你想存储任何东西,你需要它来获取Objects。 Java 不允许您操作指针,因此您不能像在 C/C++ 中那样只使用int。您也可以使用泛型,例如public class stackx&lt;T&gt;,它会给你类似stackx&lt;String&gt; newStack = new stackx&lt;&gt;(5);。

【讨论】:

    【解决方案3】:

    只需将int修改为String即可。这里是Demo。

    【讨论】:

    • 请将您的代码作为答案的一部分发布,并避免链接到外部网站。
    猜你喜欢
    • 2021-12-01
    • 2011-04-22
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多