我有一個任務將字符串推入堆棧。我創建了一個存儲數字的程序,但我無法弄清楚定義數組以獲取字符串的正確方法。這是我的代碼。我的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();
}
}
這是你在找什麼? [在Java中聲明數組](https://stackoverflow.com/questions/1200621/how-do-i-declare-and-initialize-an-array-in-java) –