计算器实现

前几天发的计算器有点问题,现在这个是新的,而且还能计算小数了

/**
* A calculator
* For example:
*  25+0.2*5-2/1.0
* @author daiwei
* @version 1.0
*/
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.*;

public class CalculatorFrame extends JPanel
{
 private static final long serialVersionUID = 1L;

 /**
  * 显示计算式子和结果
  * */
 private JTextField resultField ;
 
 /**
  * cancelButton可以清楚上次的结果,进行从新的计算
  * backButton往前删除一个字符
  * */
 private JButton cancelButton ;
 private JButton backButton ;
 
 /**
  * 定义0~9数字的按钮
  * */
 private JButton firstButton ;
 private JButton secondButton ;
 private JButton thirdButton ;
 private JButton forthButton ;
 private JButton fiveButton ;
 private JButton sixButton ;
 private JButton sevenButton ;
 private JButton eightButton ;
 private JButton nineButton ;
 private JButton zeroButton ;
 private JButton dotButton ; //暂时没有实现
 
 /**
  * 操作按钮,完成加、减、乘、除,equalButton是得到结果
  * */
 private JButton addButton ;
 private JButton subButton ;
 private JButton multiButton;
 private JButton divideButton ;
 private JButton equalButton;
 
 /**
  * 用来存放已经分析出来的数字,操作符号等
  * */
 private ArrayList operators = new ArrayList();
 /**
  * 用来存放输入的字符串
  * */
 private StringBuffer b = new StringBuffer();
 
 
 /**
  * 对控件进行布局
  * */
 public CalculatorFrame()
 {
  resultField = new JTextField("",15);
  resultField.setEditable(false);
  
  cancelButton = new JButton("CE") ;
  cancelButton.addActionListener(new CancelActionListener());
  backButton = new JButton("BackUp");
  backButton.addActionListener(new BackActionListener());
  
  firstButton = new JButton("1");
  firstButton.addActionListener(new FirstActionListener());
  
  secondButton = new JButton("2");
  secondButton.addActionListener(new SecondActionListener());
  
  thirdButton = new JButton("3");
  thirdButton.addActionListener(new ThirdActionListener());
  
  forthButton = new JButton("4");
  forthButton.addActionListener(new ForthActionListener());
  
  fiveButton = new JButton("5");
  fiveButton.addActionListener(new FiveActionListener());
  
  sixButton = new JButton("6");
  sixButton.addActionListener(new SixActionListener());
  
  sevenButton = new JButton("7");
  sevenButton.addActionListener(new SevenActionListener());
  
  eightButton = new JButton("8");
  eightButton.addActionListener(new EightActionListener());
  
  nineButton = new JButton("9");
  nineButton.addActionListener(new NineActionListener());
  
  zeroButton = new JButton("0");
  zeroButton.addActionListener(new ZeroActionListener());
  
  dotButton = new JButton(".");
  dotButton.addActionListener(new DotActionListener());
  
  addButton = new JButton("+");
  addButton.addActionListener(new AddActionListener());
  
  subButton = new JButton("-");
  subButton.addActionListener(new SubActionListener());
  
  multiButton = new JButton("*");
  multiButton.addActionListener(new MultiActionListener());
  
  divideButton = new JButton("/");
  divideButton.addActionListener(new DivideActionListener());
  
  equalButton = new JButton("=");
  equalButton.addActionListener(new EqualActionListener());
  
  GridBagLayout grid = new GridBagLayout();
  GridBagConstraints c = new GridBagConstraints();
  
  this.setLayout(grid);
  
  JPanel field = new JPanel();
  field.add(resultField);
  
  c.gridx = 1 ;
  c.gridy = 1 ;
  grid.setConstraints(field, c);
  this.add(field);
  
  JPanel line1 = new JPanel();
  line1.setLayout(new GridLayout(1,2));
  line1.add(backButton);
  line1.add(cancelButton);
  
  c.gridx = 1 ;
  c.gridy = 2 ;
  grid.setConstraints(line1, c);
  this.add(line1);
  
  JPanel part = new JPanel();
  part.setLayout(new GridLayout(4,4));
  part.add(sevenButton);
  part.add(eightButton);
  part.add(nineButton);
  part.add(addButton);
  
  part.add(forthButton);
  part.add(fiveButton);
  part.add(sixButton);
  part.add(subButton);
  
  part.add(firstButton);
  part.add(secondButton);
  part.add(thirdButton);
  part.add(multiButton);
  
  part.add(zeroButton);
  part.add(dotButton);
  part.add(equalButton);
  part.add(divideButton);
  
  c.gridx = 1 ;
  c.gridy = 3 ;
  grid.setConstraints(part, c) ;
  this.add(part);
  
 }
 /**
  * 输入数字1,将其加入到b当中,并且在结果栏显示
  * */
 class FirstActionListener implements ActionListener
 {
  public void actionPerformed(ActionEvent event)
  {
   b.append("1");
   resultField.setText(b.toString());
  }
 }
 /**
  * 输入数字2,将其加入到b当中,并且在结果栏显示
  * */
 class SecondActionListener implements ActionListener
 {
  public void actionPerformed(ActionEvent event)
  {
   b.append("2");
   resultField.setText(b.toString());
  }
 }
 /**
  * 输入数字3,将其加入到b当中,并且在结果栏显示
  * */
 class ThirdActionListener implements ActionListener
 {
  public void actionPerformed(ActionEvent event)
  {
   b.append("3");
   resultField.setText(b.toString());
  }
 }
 /**
  * 输入数字4,将其加入到b当中,并且在结果栏显示
  * */
 class ForthActionListener implements ActionListener
 {
  public void actionPerformed(ActionEvent event)
  {
   b.append("4");
   resultField.setText(b.toString());
  }
 }
 /**
  * 输入数字5,将其加入到b当中,并且在结果栏显示
  * */
 class FiveActionListener implements ActionListener
 {
  public void actionPerformed(ActionEvent event)
  {
   b.append("5");
   resultField.setText(b.toString());
  }
 }
 /**
  * 输入数字6,将其加入到b当中,并且在结果栏显示
  * */
 class SixActionListener implements ActionListener
 {
  public void actionPerformed(ActionEvent event)
  {
   b.append("6");
   resultField.setText(b.toString());
  }
 }
 /**
  * 输入数字7,将其加入到b当中,并且在结果栏显示
  * */
 class SevenActionListener implements ActionListener
 {
  public void actionPerformed(ActionEvent event)
  {
   b.append("7");
   resultField.setText(b.toString());
  }
 }
 /**
  * 输入数字8,将其加入到b当中,并且在结果栏显示
  * */
 class EightActionListener implements ActionListener
 {
  public void actionPerformed(ActionEvent event)
  {
   b.append("8");
   resultField.setText(b.toString());
  }
 }
 /**
  * 输入数字9,将其加入到b当中,并且在结果栏显示
  * */
 class NineActionListener implements ActionListener
 {
  public void actionPerformed(ActionEvent event)
  {
   b.append("9");
   resultField.setText(b.toString());
  }
 }
 /**
  * 输入数字0,将其加入到b当中,并且在结果栏显示
  * */
 class ZeroActionListener implements ActionListener
 {
  public void actionPerformed(ActionEvent event)
  {
   b.append("0");
   resultField.setText(b.toString());
  }
 }
 /**
  * 输入符号.,将其加入到b当中,并且在结果栏显示
  * */
 class DotActionListener implements ActionListener
 {
  public void actionPerformed(ActionEvent event)
  {
   b.append(".");
   resultField.setText(b.toString());
  }
 }
 /**
  * 输入符号+,将其加入到b当中,并且在结果栏显示
  * */
 class AddActionListener implements ActionListener
 {
  public void actionPerformed(ActionEvent event)
  {
   b.append("+");
   resultField.setText(b.toString());
  }
 }
 /**
  * 输入符号-,将其加入到b当中,并且在结果栏显示
  * */
 class SubActionListener implements ActionListener
 {
  public void actionPerformed(ActionEvent event)
  {
   b.append("-");
   resultField.setText(b.toString());
  }
 }
 /**
  * 输入符号*,将其加入到b当中,并且在结果栏显示
  * */
 class MultiActionListener implements ActionListener
 {
  public void actionPerformed(ActionEvent event)
  {
   b.append("*");
   resultField.setText(b.toString());
  }
 }
 /**
  * 输入符号/,将其加入到b当中,并且在结果栏显示
  * */
 class DivideActionListener implements ActionListener
 {
  public void actionPerformed(ActionEvent event)
  {
   b.append("/");
   resultField.setText(b.toString());
  }
 }
 /**
  * 按下等号时,进行计算的具体操作
  * */
 class EqualActionListener implements ActionListener
 {
  public void actionPerformed(ActionEvent event)
  {
   b.append('=') ;
   int i = 0;
   char currentChar ;
   
   while(i<b.length())
   {
    currentChar = b.charAt(i);
    /**
     * 判断得到数字,并且存入到operators里面,注意此时已经将小数判定在内
     * */
    if(isDigit(currentChar) || isDot(currentChar))
    {
     StringBuffer n = new StringBuffer();
     n.append(currentChar);
     i++ ;
     while(i<b.length())
     {
      if(isDigit(b.charAt(i)) || isDot(b.charAt(i)))
      {
       n.append(b.charAt(i));
       i++;
      }
      else
       break ;
     }
     operators.add(Double.parseDouble(n.toString()));
    }
    /**
     * 判断当前字符是否为'+'或者'-',如果是直接存入到operators中
     * */
    if(isLowOperate(currentChar))
    {
     operators.add(currentChar);
     i++ ;
    }
    /**
     * 如果当前字符是一个高优先级字符'*'或者'/',取出operators中的最
     * 后面的一个元素作为op1,然后得到运算符后的操作数为op2,最后将op1
     * 和op2进行计算得到的结果存入到operators中
     * */
    if(isHighOperate(currentChar))
    {
     double op1 = Double.parseDouble((operators.get(operators.size()-1)).toString());
     double op2 = 0.0 ;
     char op = currentChar ;
     double result = 0.0 ;
     i++;
     if(isDigit(b.charAt(i)) || isDot(b.charAt(i)))
     {
      StringBuffer n = new StringBuffer();
      n.append(b.charAt(i));
      i++ ;
      while(i<b.length())
      {
       if(isDigit(b.charAt(i)) || isDot(b.charAt(i)))
       {
        n.append(b.charAt(i));
        i++;
       }
       else
        break ;
      }
      op2 = Double.parseDouble(n.toString());
     }
     else
     {
      JOptionPane.showMessageDialog(null, "算术式子出错!");
     }
     
     if(op=='*')
     {
      result = op1 * op2 ;
     }
     else if(op=='/')
     {
      if(op2==0.0)
      {
       JOptionPane.showMessageDialog(null, "除数不能为零!");
      }
      else
         result = op1 / op2 ;
     }
     operators.set(operators.size()-1, result);
    }
    /**
     * 计算最后的结果,由于在上面进行了优先级的控制,所以说在这个时候所有
     * 的运算只有+和-,一次读出数字,然后计算结果,并将结果显示
     * */
    if(isEnd(currentChar))
    {
           for(int m=0 ; m<operators.size() ;m++)
           {
            System.out.println("the operators are: "+operators.get(m));
           }
     double totalResult = 0.0 ;
     double op1 = 0.0 ;
     double op2 = 0.0 ;
     String op = "";
     
     int j = 0;
     
     op1 = Double.parseDouble(operators.get(j).toString());
     j++ ;
     totalResult = op1 ;
     
     while(j<operators.size())
     {
      op = operators.get(j).toString();
      j++ ;
      if(j<operators.size())
      {
       op2 = Double.parseDouble(operators.get(j).toString());
       j++ ;
       if(op.equals("+"))
       {
        totalResult = totalResult + op2 ;
       }
       else if(op.equals("-"))
       {
        totalResult = totalResult - op2 ;
       }
      }
      else
       JOptionPane.showMessageDialog(null, "计算式子出错!");
      
     }
     
     b.delete(0, b.length());
     operators.clear();
     operators.add(totalResult);
     resultField.setText(Double.toString(totalResult));
     i++ ;
    }
   }
  }
  /**
   * 判断当前字符是否为数字
   * */
  public boolean isDigit(char currentChar)
  {
   if(currentChar=='0' || currentChar=='1'|| currentChar=='2' || currentChar=='3' || currentChar=='4'
    || currentChar=='5' || currentChar=='6' || currentChar=='7' || currentChar=='8' || currentChar=='9')
   {
    return true ;
   }
   return false;
  }
  /**
   * 判断当前字符是否为+或-
   * */
  public boolean isLowOperate(char currentChar)
  {
   if(currentChar=='+' || currentChar=='-')
   {
    return true ;
   }
   return false;
  }
  /**
   * 判断当前字符是否为*或/
   * */
  public boolean isHighOperate(char currentChar)
  {
   if(currentChar=='*' || currentChar=='/')
   {
    return true;
   }
   return false;
  }
  /**
   * 判断当前字符是否为'='
   * */
  public boolean isEnd(char currentChar)
  {
   if(currentChar=='=')
   {
    return true ;
   }
   return false ;
  }
  public boolean isDot(char currentChar)
  {
   if(currentChar =='.')
   {
    return true ;
   }
    return false ;
  }
 }
 /**
  * 取消按钮响应,清除所有的记录,开始新的计算
  * */
 class CancelActionListener implements ActionListener
 {
  public void actionPerformed(ActionEvent event)
  {
   b.delete(0, b.length());
   operators.clear();
   resultField.setText("");
  }
 }
 /**
  * 向前按钮相应,往前清除一个字符
  * */
 class BackActionListener implements ActionListener
 {
  public void actionPerformed(ActionEvent event)
  {
   b.delete(b.length()-1, b.length());
   resultField.setText(b.toString());
  }
 }
 
 public static void main(String args[])
 {
  
  JFrame frame = new JFrame("JLabelDemo");

        frame.setContentPane(new CalculatorFrame());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();    // Adjust the size of the window
        frame.setVisible(true);
        frame.setSize(230,230);

 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值