[英]JAVA - How do you push a string into a stack?
我有一個分配將字符串推入堆棧的任務。 我創建了一個存儲數字的程序,但是我無法弄清楚定義數組以接收字符串的正確方法。 這是我的代碼。 我的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();
}
}
您的堆棧只需要int
。 如果要存儲任何內容,則需要使用Object
。 Java不允許您操作指針,因此不能像在C / C ++中那樣僅使用int
。 您也可以使用泛型,例如public class stackx<T>
,它將為您提供諸如stackx<String> newStack = new stackx<>(5);
。
這應該很容易,我將為您提供一個小提示,如果您仍然無法弄清楚,當您聲明這樣的內容時,我將發布整個代碼
private int[] stackArray;
並使用此數組來推送和彈出您的項目,因為這是Integer數組,因此您只能將此實現用於Integers。
現在您的要求是推入並彈出字符串,因此從本質上講您應該執行類似的操作。
private String[] stackArray;
注意:您的Push和pop方法將同樣發生變化,這些變化很小
希望這可以幫助!
祝好運。
只需將int
修改為String
。這是Demo 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.