JAVA - 你如何将一个字符串推入堆栈?
问题描述:
我有一个任务将字符串推入堆栈。我创建了一个存储数字的程序,但我无法弄清楚定义数组以获取字符串的正确方法。这是我的代码。我的Java很生疏,所以我正在尝试从2年前的第一个Java类中记住所有这些。我确信它非常简单,但我无法在网上找到任何字符串存储在堆栈中的任何信息,以便我了解如何执行此操作。谢谢您的帮助!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();
}
}
答
这应该是容易的,我会提供你一个小提示,如果你仍然无法弄清楚,我会后整个代码 当你声明是这样的
private int[] stackArray;
,并使用这个数组推动和弹出你的项目,因为这是Integer数组,你只能在Integers中使用这个实现。
现在你的要求是推动和弹出字符串,所以基本上你应该这样做。
private String[] stackArray;
注:您的push和pop方法同样会发生变化,这些将是微小的变化
希望这有助于!
祝你好运。
答
您的堆栈只需要int
s。如果你想存储任何东西,你需要它采取Object
。 Java不允许你操作指针,所以你不能像在C/C++中一样使用int
。您也可以使用泛型,例如public class stackx<T>
,这会给你类似stackx<String> newStack = new stackx<>(5);
。
这是你在找什么? [在Java中声明数组](https://stackoverflow.com/questions/1200621/how-do-i-declare-and-initialize-an-array-in-java) –