package test;

import javax.swing.;

import java.awt.
;

import java.awt.event.KeyAdapter;

import java.awt.event.KeyEvent;

import java.util.HashMap;

import java.util.Stack;

/**

  • Created by zxx on 2020/10/15.

    */

    public class Calculator extends JFrame{

    private Stack operandStack= new Stack<>();

    private Stack operatorStack = new Stack<>();

    private Calculator(){

     setTitle("计算器");
    setSize(266,340);
    //setSize(400,540);
    Container c=getContentPane();
    c.setLayout(null); JTextArea jt=new JTextArea(100,100);
    jt.setFont(new Font("Aria",Font.BOLD,32));
    jt.setLineWrap(true);
    JScrollPane sp=new JScrollPane(jt);
    jt.setCaretPosition(jt.getDocument().getLength());
    sp.setBounds(0,0,250,100);
    c.add(sp); JPanel p=new JPanel();
    p.setLayout(new GridLayout(5,4,0,0)); p.setBounds(0,100,250,200);
    String[] num={"(",")","AC","/","7","8","9","*","4","5","6","-","1","2","3","+","0",".","DEL","="};
    JButton[] jb=new JButton[20];
    for(int i=0;i<20;i ++ ){
    jb[i]=new JButton(num[i]);
    p.add(jb[i]);
    }
    c.add(p); for(int i=0;i<18;i ++){
    if(i!=2){
    final int j=i;
    jb[i].addActionListener(e-> jt.append(num[j]));
    }
    } jb[2].addActionListener(e->{
    jt.setText("");
    operandStack.clear();
    operatorStack.clear();
    });
    jb[18].addActionListener(e->{
    try{
    jt.setText(jt.getText().substring(0,jt.getText().length()-1));
    }catch(Exception ignored) { }//忽略这个异常 IDEA就是好用!!!
    });
    jb[19].addActionListener(e->{
    try{
    double x= calculate(jt.getText()+ "#");
    jt.setText("");
    jt.append(String.valueOf(x));
    }catch(Exception ex){
    if(ex.getMessage()==null)
    jt.setText("ERROR!");
    else
    jt.setText(ex.getMessage());
    }
    });
    //禁止文本域的enter换行
    KeyStroke enter = KeyStroke.getKeyStroke("ENTER");
    jt.getInputMap().put(enter, "none"); this.getRootPane().setDefaultButton(jb[19]); c.addKeyListener(new KeyAdapter() {
    @Override
    public void keyTyped(KeyEvent e)
    { }
    public void keyPressed(KeyEvent e) //键盘按键监听
    {
    char label=e.getKeyChar();
    String k=String.valueOf(label);
    if(label==KeyEvent.VK_ENTER)
    {
    calculate();
    }
    else if(label==KeyEvent.VK_BACK_SPACE)
    {
    String s = jt.getText();
    if(s!=null)
    {
    calculate(); //调用定义的处理←方法
    }else
    {
    jt.setText(s);
    }
    }
    else
    {
    calculate(k); //按下数字和运算符号的叠加
    }
    }
    public void keyReleased(KeyEvent e)
    { } }); setVisible(true);
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    }

    private void calculate(){

    String b = operatorStack.pop();

    double c = operandStack.pop();

    double d = operandStack.pop();

    double e;

    if (b.equals("+")) {

    e = d + c;

    operandStack.push(e);

    }

    if (b.equals("-")) {

    e = d - c;

    operandStack.push(e);

    }

    if (b.equals("*")) {

    e = d * c;

    operandStack.push(e);

    }

    if (b.equals("/")) {

    if(c==0)

    throw new ArithmeticException("DivideByZero!");//不可修改为Exception

    // Exception的异常是必须处理的,是受控异常;而ArithmeticException 不是必须处理的 ,受控异常必须强制处理

    e = d / c;

    operandStack.push(e);

    }

    }

    private Double calculate(String text){

    HashMap<String,Integer> precede=new HashMap<>();

    precede.put("(",0);

    precede.put(")",0);

    precede.put("/",2);

    precede.put("*",2);

    precede.put("-",1);

    precede.put("+",1);

    precede.put("#",0);

     operatorStack.push("#");
    
     int flag=0;
    for(int i=0;i<text.length();i++ ){
    String a=String.valueOf(text.charAt(i));
    if(!a.matches("[0-9.]")){
    if(flag!=i)
    operandStack.push(Double.parseDouble(text.substring(flag,i)));
    flag=i+ 1;
    while(!(a.equals("#")&&operatorStack.peek().equals("#"))){
    if(precede.get(a)>precede.get(operatorStack.peek())||a.equals("(")){
    operatorStack.push(a);
    break;
    }else {
    if(a.equals(")")) {
    while(!operatorStack.peek().equals("("))
    calculate();
    operatorStack.pop();
    break;
    }
    calculate();
    }
    } }
    } return(operandStack.pop());

    }

    public static void main(String[] args){

    new Calculator();

    }

    }

最新文章

  1. Junit测试Controller(MockMVC使用),传输@RequestBody数据解决办法
  2. 关于Git和Github你不知道的十件事
  3. shell实现https登录
  4. laravel框架中Email邮件配置
  5. CHANGE DEFAULT FTP PORT FOR VSFTP
  6. 将含有父ID的列表转成树
  7. C#核编之格式化编程
  8. centos7 opera济览器安装
  9. android项目--上下文菜单
  10. Oracle实战笔记(第三天)
  11. 微服务SpringCloud—Config Server对称加密
  12. 调试利器GDB(上)
  13. 在Unity 3D中加入Image图片
  14. python基础学习(十三)函数进阶
  15. 【Window 7】解决Win7远程桌面无法全屏的方法
  16. Java面向对象-------多态总结
  17. 记一次服务器迁移后的nginx启动问题
  18. C#string与stringBuilder的区别
  19. Java IO的应用之实现大文件复制
  20. 广州工业大学2016校赛 F 我是好人4 dfs+容斥

热门文章

  1. C#知识点:抽象类和接口浅谈
  2. pytest allure 生成html测试报告
  3. 微信小程序 部署(后台是springboot项目 前后台分流)
  4. HTML标签语言一览表
  5. 微信小程序入门到精通[更新版]
  6. 1.5Hadoop的启动
  7. 基本的PID算法整理(水缸的例子有问题!!)
  8. python-文本操作和二进制储存
  9. Oracle学习(十四)分表分区
  10. Sublime Text3 for Java 编译运行环境配置 入门详解 - 精简归纳