 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;
 import java.util.*;
 
 public class Calculater {

   private JFrame frame;
   private JPanel panel;
   private JTextField tf; 	
   private JButton b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,bAdd,bDel,bMul,bDiv,bClear,bEqual;

   LinkedList<String> v=new LinkedList<String>();//用来存放表达式
      
   public static void main(String args[]) { 
     Calculater gui = new Calculater(); 
     gui.go();
   } 

   public void go() { 
             
     //设置主界面
     frame = new JFrame("Calculater");
     panel = new JPanel();
     tf=new JTextField();
     tf.setBackground(Color.WHITE); 	
     frame.add(tf,BorderLayout.NORTH); 	
     frame.add(panel,BorderLayout.CENTER); 				 
             
     //设置按钮面板
     b0=new JButton("0");		
     b1=new JButton("1");	
     b2=new JButton("2");	
     b3=new JButton("3");	
     b4=new JButton("4");	
     b5=new JButton("5");	
     b6=new JButton("6");	
     b7=new JButton("7");	
     b8=new JButton("8");	
     b9=new JButton("9");	
     bAdd=new JButton("+");	
     bDel=new JButton("-");	
     bMul=new JButton("*");	
     bDiv=new JButton("/");	
     bClear=new JButton("C");	
     bEqual=new JButton("=");	
             
     panel.setLayout(new GridLayout(4,4));
     panel.add(b7);	   
     panel.add(b8);	
     panel.add(b9);	
     panel.add(bAdd);	
     panel.add(b4);	
     panel.add(b5);	
     panel.add(b6);	
     panel.add(bDel);	
     panel.add(b1);	
     panel.add(b2);	
     panel.add(b3);	
     panel.add(bMul);	
     panel.add(b0);	
     panel.add(bClear);	
     panel.add(bEqual);	
     panel.add(bDiv);	

     MyActionListener ma=new MyActionListener();
             
     b0.addActionListener(ma);   
     b1.addActionListener(ma);   
     b2.addActionListener(ma);   
     b3.addActionListener(ma);   
     b4.addActionListener(ma);   
     b5.addActionListener(ma);   
     b6.addActionListener(ma);   
     b7.addActionListener(ma);   
     b8.addActionListener(ma);   
     b9.addActionListener(ma);   
     bAdd.addActionListener(ma);   
     bDel.addActionListener(ma);   
     bMul.addActionListener(ma);   
     bDiv.addActionListener(ma);   
     bEqual.addActionListener(ma);   
     bClear.addActionListener(ma);   
             
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     frame.setSize(300,300);
     frame.setVisible(true); 
  }
         
      
  //内部类，响应用户按下按钮的操作    
  class MyActionListener implements ActionListener{
    public void actionPerformed(ActionEvent evt){
      JButton b=(JButton)evt.getSource();
      if(b==bEqual)
        calculateLinkedList();
      else{ 
        if(b==bClear)
          clearLinkedList();
        else{
          String element=b.getText();
          String elementLast=null;
          if(v.size()!=0){
             elementLast=v.get(v.size()-1);
             if(isNum(element) && !isNum(elementLast) || isNum(elementLast)){
               v.addLast(element);
               printLinkedList();
             }
          }else{
            if(isNum(element)){
              v.addLast(element);
              printLinkedList();
            }
          }
        }
      }
    }
            
    public void printLinkedList(){
      String s="";
      for(String e:v){
        s=s+e;
      }
      tf.setText(s);
    }
    public boolean isNum(String s){
      boolean b;
      try{
        Integer.parseInt(s);
        return true;
      }catch(Exception e){return false;}
    }
        
    public void calculateLinkedList(){
      if(v.size()==0) return;
            
      //过滤表达式，将多个数字合并为一个整数，放入新的列表vv中
      //如果在列表v中为{"1","2","+","1","*","2"}
      //则列表vv中内容为{"12","+","1","*","2"}
            
      LinkedList<String> vv=new LinkedList<String>();
      int index=0;
      while(index<v.size()){
        int num=0;
        while(index<v.size() && isNum((String)v.get(index))){
          num=num*10+Integer.parseInt((String)v.get(index));
          index++;
        }
        vv.addLast(new Integer(num).toString());
        if(index<v.size()&& index!=v.size()-1)vv.addLast(v.get(index));
                
        index++;
            
      }
            
      int result=0;
      if(vv.size()<3)
        result=Integer.parseInt((String)vv.get(0));
      else             
        result=calculateLinkedList(vv);
         
      tf.setText(new Integer(result).toString());
      v.clear();
      v.addLast(tf.getText());
    }
        
    //采用递归计算表达式
    public int calculateLinkedList(LinkedList<String> vv){
      String num1=(String)vv.get(0);
      String opt=(String)vv.get(1);
      String num2=(String)vv.get(2);
            
      if(vv.size()==3)return calculate(num1,opt,num2);
      if(opt.equals("*") || opt.equals("/")){
        // 对于表达式1*2+12-2， 先计算1*2＝2, 再计算表达式2＋12－2
        int result=calculate(num1,opt,num2);
        vv.remove(0);
        vv.remove(0);
        vv.remove(0);
                
        vv.add(0,new Integer(result).toString());
        return calculateLinkedList(vv);
      }else{
        /* 对于表达式12+1*2-3， 可以把它看作12+(1*2-3)，
           先计算1*2-3＝－1，再计算表达式12＋（－1）＝11 */

        /* 对于表达式12-1*2-3， 可以把它看作12-(1*2+3)，
           先计算1*2+3＝5，再计算表达式12-5＝7 */
  
        vv.remove(0);
        vv.remove(0);
            
        //当操作符为“-”，把操作符右边的表达式中的“+”改为“-”，“-”改为“+”
        if(opt.equals("-"))vv=negateLinkedList(vv);
        num2=new Integer(calculateLinkedList(vv)).toString();
        return calculate(num1, opt, num2); 
      }
    }
        
    public int calculate(String num1, String opt,String num2){
      int result=Integer.parseInt(num1);
      switch(opt){
        case "+":result=result+Integer.parseInt(num2);break;
        case "-":result=result-Integer.parseInt(num2);break;
        case "*":result=result*Integer.parseInt(num2);break;
        case "/":result=result/Integer.parseInt(num2);
      }      
      System.out.println(num1+opt+num2+"="+result);  //跟踪计算过程
      return result;
    }
 
    //把表达式中的“+”改为“-”，“-”改为“+”
    public LinkedList<String>  negateLinkedList(LinkedList<String>  vv){
       LinkedList<String> v=new  LinkedList<String>(); 
       for(String s:vv)
         switch(s){
           case "+": v.add("-");break;

           case "-": v.add("+");break;
           default: v.add(s); 
         }
      
       return v;
    } 
      
    public void clearLinkedList(){
      v.clear();
      tf.setText(null);
    }
  }//End of Inner Class
}
 
/****************************************************
 * 作者：孙卫琴                                     *
 * 来源：<<Java面向对象编程>>                       *
 * 技术支持网址：www.javathinker.net                *
 ***************************************************/


