2015-07-20 312 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); 


}