2015-07-20 307 views
-1

好吧,這是我的數組堆棧從我的主要分開 我只有一個問題,但我的代碼沒有問題,但它缺乏 東西就像如果我運行流行但棧是空的,它必須有一個對話說它是空的,我試過一個if else語句,但我不知道該把它放在哪裏,或者是否真的需要if else語句,反正這裏是我的代碼。 。 。如何檢查堆棧是否爲空

public class ArrayStack { 
     int STACK_MAX = 20; 
     int size = -1 ; 
     int top = -1 ; 
     int StackObj[] = new int[STACK_MAX]; 

      /**************** for PUSH METHOD *********/ 

     public void Push(int obj) { 
      if (size()==STACK_MAX){ 
       System.out.println("STACK is FULL"); 
       } 
      else{ 
        StackObj[++top]= obj; 
       } 
     } 

     /**************** for SIZE Method ********/ 

     public int size() { 
      return (top+1);  
     } 

     /******************** for Display Method****/ 

     public void DisplayStack() { 
       String disp=""; 

       for (int i=top; i>=0; i--){ 
        disp += StackObj[i] + "\n";      
       } 
       JOptionPane.showMessageDialog(null, "Elements of the Stacks : \n" + disp); 
      } 

     /***************** for isEmpty Method *******/ 

     public boolean isEmpty(){ 

     return (top == -1); 

     } 

     /***************** for Top Method ***********/ 
     public int Topmethod(){ 

     int taas = StackObj[top]; 

     JOptionPane.showMessageDialog(null,"Top is : "+taas); 
     return (top); 
     } 

     /***************** for Pop Method ***********/  
      public int pop(){ 

      int topItem = StackObj[top]; 
       top--; 
      JOptionPane.showMessageDialog(null,"The recently pushed number was Deleted: "+topItem); 
      return(top); 
     } 
    } 
+1

你能否讓你的標題與你的實際問題更相關?在編輯器中也有'{}'選項,它允許您正確地發佈代碼示例。 – Pshemo

+0

所有使用小寫字母的單詞都很難閱讀,例如試圖聽別人嘟someone。請在句子的開頭使用大寫字母,單詞I以及諸如'ArrayList'或Oracle的專有名稱。 –

+0

'if(isEmpty()){JOptionPane.showMessage(); }'扔在流行的方法。 – Adam

回答

0

你會想在你的pop方法添加的東西來處理承認當堆棧是空的,然後處理空棧等的情況下:

public int pop(){ 
    if(size() == 0){ //detect empty stack 
     JFrame frame = new JFrame("my frame");; //handle empty stack 
     JOptionPane.showMessageDialog(frame,"Stack is empty!"); 
     return null; //make sure you handle a null return value if you use this 
    } 
    int topItem = StackObj[top]; 
     top--; 
    JOptionPane.showMessageDialog(null,"The recently pushed number was Deleted: "+topItem); 
    return(top); 


} 
+0

把你的'system.out'改成'JOptionPane.showMessageDialog',你就會明白他在找什麼。 – Adam

+0

哦抱歉沒有看到他要求彈出一個對話,謝謝 - 現在編輯 – GregH

+0

謝謝佩吉我改變了它雖然因爲我不使用框架。 。 。它就像這樣 – MarvintOy

0

在這裏,我剪輯

public int pop(){ 
    if(size() == 0){ //detect empty stack 
    JOptionPane.showMessageDialog(null,"Stack is empty!"); 
    return (top); //make sure you handle a null return value if you use this 
} 
    int topItem = StackObj[top]; 
     top--; 
    JOptionPane.showMessageDialog(null,"The recently pushed number was Deleted: "+topItem); 
    return(top); 


}