2017-06-02 61 views
0

我有一個任務將字符串推入堆棧。我創建了一個存儲數字的程序,但我無法弄清楚定義數組以獲取字符串的正確方法。這是我的代碼。我的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(); 
      } 
     } 
+1

這是你在找什麼? [在Java中聲明數組](https://stackoverflow.com/questions/1200621/how-do-i-declare-and-initialize-an-array-in-java) –

回答

0

這應該是容易的,我會提供你一個小提示,如果你仍然無法弄清楚,我會後整個代碼 當你聲明是這樣的

private int[] stackArray; 

,並使用這個數組推動和彈出你的項目,因爲這是Integer數組,你只能在Integers中使用這個實現。

現在你的要求是推動和彈出字符串,所以基本上你應該這樣做。

private String[] stackArray; 

注:您的push和pop方法同樣會發生變化,這些將是微小的變化

希望這有助於!

祝你好運。

+0

謝謝!這工作。我試了幾次,但一定是失去了別的東西。我刪除了我的整個代碼並重寫了它,然後它工作:) – Scott

+0

@ Scott很棒,很高興知道 – Vihar

0

您的堆棧只需要int s。如果你想存儲任何東西,你需要它採取Object。 Java不允許你操作指針,所以你不能像在C/C++中一樣使用int。您也可以使用泛型,例如public class stackx<T>,這會給你類似stackx<String> newStack = new stackx<>(5);

0

只是修改intString。這裏是Demo

+2

請將您的代碼作爲答案的一部分發布,並避免鏈接到外部網站。 – Confiqure