赞
踩
本人大一新手小白一枚,今天是我开通博客的第一天,发个java计算器纪念一下。
诸位有意见可以提,有不懂的也可以问,但不保证才疏学浅的博主能回答上来
希望以后能和你们一起共同进步,共勉!
先放上博主的代码
下面的是界面和一部分运算代码:
- import java.awt.*;
- import javax.swing.*;
- import java.awt.event.*;
- public class Calculator extends JFrame
- {
- static JFrame frame=new JFrame("计算器");
- JTextField display=new JTextField("0");
- Font font=new Font("Consolas",Font.BOLD,40); //设置字体样式
- Font font1=new Font("Consolas",Font.BOLD,20);
- Image iconImage=(new ImageIcon("C:\\Study\\eclipse-workspace\\Calculator\\src\\计算器2.png")).getImage();
- ImageIcon iconImage2=new ImageIcon("C:\\Study\\eclipse-workspace\\Calculator\\src\\删除.png");
- actionlistener al=new actionlistener();//创建监听器action listener的对象
-
- //计算器按键
- JButton button_clear=new JButton("C");
- JButton button_delete=new JButton(iconImage2);
- JButton button_plus=new JButton("+");
- JButton button_minus=new JButton("-");
- JButton button_multiply=new JButton("*");
- JButton button_divide=new JButton("/");
- JButton button_spot=new JButton(".");
- JButton button_is=new JButton("=");
- JButton button_sin=new JButton("sin");
- JButton button_cos=new JButton("cos");
- JButton button_tan=new JButton("tan");
- JButton button_log=new JButton("log");
- JButton button_bracket_r=new JButton("(");
- JButton button_bracket_l=new JButton(")");
- JButton[] button=new JButton[10];
-
- public Calculator()
- {
- super();
-
- //设置按钮颜色字体和监听器
- for (int i = 0; i < 10; i++)
- {
- button[i] = new JButton(""+i);
- button[i].setBackground(Color.white);//设置按钮颜色
- button[i].setFont(font1); //设置按钮字体
- button[i].addActionListener(al); //注册监听器
- }
- //设置按钮颜色
- button_plus.setBackground(Color.white);
- button_is.setBackground(Color.pink);
- button_minus.setBackground(Color.white);
- button_multiply.setBackground(Color.white);
- button_divide.setBackground(Color.white);
- button_spot.setBackground(Color.white);
- button_clear.setBackground(Color.white);
- button_delete.setBackground(Color.white);
- button_sin.setBackground(Color.white);
- button_cos.setBackground(Color.white);
- button_tan.setBackground(Color.white);
- button_log.setBackground(Color.white);
- button_bracket_r.setBackground(Color.white);
- button_bracket_l.setBackground(Color.white);
- //设置按键透明
- button_sin.setOpaque(false);
- button_cos.setOpaque(false);
- button_log.setOpaque(false);
- button_tan.setOpaque(false);
- button_plus.setOpaque(false);
- button_minus.setOpaque(false);
- button_multiply.setOpaque(false);
- button_divide.setOpaque(false);
- button_spot.setOpaque(false);
- //设置按钮字体
- button_plus.setFont(font1);
- button_is.setFont(font1);
- button_minus.setFont(font1);
- button_multiply.setFont(font1);
- button_divide.setFont(font1);
- button_spot.setFont(font1);
- button_clear.setFont(font1);
- button_delete.setFont(font1);
- button_sin.setFont(font1);
- button_cos.setFont(font1);
- button_tan.setFont(font1);
- button_log.setFont(font1);
- button_bracket_r.setFont(font1);
- button_bracket_l.setFont(font1);
-
- //计算器界面布局
- frame.setIconImage(iconImage);
- display.setHorizontalAlignment(JTextField.RIGHT);
- display.setFont(font);
- display.setBackground(Color.white);
- display.setEditable(false); //设置文本框不可编辑
-
- JPanel pan1=new JPanel(); //设置文本框布局
- pan1.setLayout(new GridLayout(1,1,5,5));
- pan1.setBorder(BorderFactory.createEmptyBorder(5, 5, 0, 5));
- pan1.add(display);
-
- JPanel panBody=new JPanel(); //将按键加入panBody中
- panBody.setLayout(new GridLayout(6,4));
- panBody.add(button_clear);
- panBody.add(button_delete);
- panBody.add(button_bracket_r);
- panBody.add(button_bracket_l);
- panBody.add(button_sin);
- panBody.add(button_cos);
- panBody.add(button_tan);
- panBody.add(button_log);
- panBody.add(button[7]);
- panBody.add(button[8]);
- panBody.add(button[9]);
- panBody.add(button_plus);
- panBody.add(button[4]);
- panBody.add(button[5]);
- panBody.add(button[6]);
- panBody.add(button_minus);
- panBody.add(button[1]);
- panBody.add(button[2]);
- panBody.add(button[3]);
- panBody.add(button_multiply);
- panBody.add(button_divide);
- panBody.add(button[0]);
- panBody.add(button_spot);
- panBody.add(button_is);
- panBody.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
-
-
- //创建框架窗口
- frame.setLayout(new BorderLayout()); //布局
- frame.add(pan1,BorderLayout.NORTH);
- frame.add(panBody,BorderLayout.CENTER);
- frame.setSize(480, 380); //大小
- frame.setLocation(260, 150); //位置
- frame.setVisible(true);
- frame.setResizable(false);
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
-
- //注册监听器
- button_plus.addActionListener(al);
- button_minus.addActionListener(al);
- button_multiply.addActionListener(al);
- button_divide.addActionListener(al);
- button_is.addActionListener(al);
- button_spot.addActionListener(al);
- button_clear.addActionListener(al);
- button_delete.addActionListener(al);
- button_sin.addActionListener(al);
- button_cos.addActionListener(al);
- button_tan.addActionListener(al);
- button_log.addActionListener(al);
- button_bracket_r.addActionListener(al);
- button_bracket_l.addActionListener(al);
-
- //设置热键
- button[0].setMnemonic(KeyEvent.VK_0);
- button[1].setMnemonic(KeyEvent.VK_1);
- button[2].setMnemonic(KeyEvent.VK_2);
- button[3].setMnemonic(KeyEvent.VK_3);
- button[4].setMnemonic(KeyEvent.VK_4);
- button[5].setMnemonic(KeyEvent.VK_5);
- button[6].setMnemonic(KeyEvent.VK_6);
- button[7].setMnemonic(KeyEvent.VK_7);
- button[8].setMnemonic(KeyEvent.VK_8);
- button[9].setMnemonic(KeyEvent.VK_9);
- button_delete.setMnemonic(KeyEvent.VK_BACK_SPACE);
- button_clear.setMnemonic(KeyEvent.VK_CLEAR);
- button_spot.setMnemonic(KeyEvent.VK_PERIOD);
- button_is.setMnemonic(KeyEvent.VK_EQUALS);
- button_plus.setMnemonic(KeyEvent.VK_ADD);
- button_minus.setMnemonic(KeyEvent.VK_SUBTRACT);
- button_multiply.setMnemonic(KeyEvent.VK_MULTIPLY);
- button_divide.setMnemonic(KeyEvent.VK_SLASH);
- }
-
-
- //定义处理事件的类
- public class actionlistener implements ActionListener
- {
- RPN rpn;
- public String pre_display="";
- public void actionPerformed(ActionEvent e)
- {
- Object click1=e.getSource(); //获得组件名称
- String click2=e.getActionCommand(); //获得组件标签
- if(click1==button_clear) //初始化文本框
- {
- pre_display="";
- display.setText("0");
- }
- else if(click1==button_delete) //用handleClear()方法处理delete
- {
- if(!pre_display.equals(""))
- display.setText(handleDelete(pre_display));
- else
- display.setText(handleDelete(display.getText()));
- }
- else if(click2=="=")
- {
- //计算表达式
- rpn=new RPN(display.getText());
- rpn.ListPreExpressionToListExpression();
- if(rpn.Opera_ListExpr().equals("illegal!"))
- display.setText("illegal!");
- else if(rpn.Opera_ListExpr().equals("non-existent!"))
- display.setText("non-existent!");
- else
- {
- double result=Double.valueOf(rpn.Opera_ListExpr()).doubleValue();
- //数据类型转换
- long t1=(long)result;
- double t2=result-t1;
- if(t2==0)
- display.setText(String.valueOf(t1));
- else
- display.setText(String.valueOf(result));
- }
-
- pre_display="";
- }
-
- else
- {
- if(click2=="tan")
- click2="tan(";
- else if(click2=="sin")
- click2="sin(";
- else if(click2=="cos")
- click2="cos(";
- else if(click2=="log")
- click2="log(";
- pre_display+=click2;
- display.setText(pre_display);
- }
- }
-
-
- //退格键
- public String handleDelete(String text)
- {
- int textLength=text.length();
- if(textLength>0)
- {
- text=text.substring(0, textLength-1); //去掉最后一个字符
- if(text.length()==0) //若文本框为空,则初始化为“0”
- {
- text="0";
- }
- pre_display=text;
- return text;
- }
- else
- return "illegal!";
- }
-
- }
- public static void main(String[] args)
- {
- Calculator calculator=new Calculator();
- }
- }
下面是逆波兰算法实现运算的代码:
- import java.util.ArrayList;
- import java.util.Stack;
- import java.util.StringTokenizer;
- public class RPN
- {
- private Stack<String> StackOperator=new Stack<>(); //存放运算符的栈
- private ArrayList<String> ListPreExpression=new ArrayList<String>(); //存放原表达式
- private ArrayList<String> ListExpression=new ArrayList<String>(); //存放逆波兰表达式
- private Stack<String> StackOperation=new Stack<>(); //运算栈
-
- //分割表达式(初始化)
- public RPN (String PreExpression)
- {
- //以+-*/()为分割符,对原始表达式(字符串)进行分割,并返回分割符
- StringTokenizer stringTokenizer=new StringTokenizer(PreExpression,"\\+|\\-|\\*|\\/|\\(|\\)",true);
- while(stringTokenizer.hasMoreTokens())
- {
- ListPreExpression.add(stringTokenizer.nextToken());
- }
- }
-
-
- //判断是否为运算符
- public boolean isOperator(String str)
- {
- if("+-*/tancossinlog()".indexOf(str)>=0)
- return true;
- else
- return false;
- }
-
- //获取运算符的优先级
- public int getPriority(String str)
- {
- int a;
- switch(str)
- {
- case "+":
- case "-":a=1;break;
- case "*":
- case "/":a=2;break;
- case "(":a=4;break;
- case ")":a=0;break;
- case "tan":
- case "sin":
- case "cos":
- case "log":a=3;break;
- default: a=-1;break;
- }
- return a;
- }
-
- //比较优先级大小
- public boolean ComparePriority(String str1,String str2)
- {
- return getPriority(str1)>getPriority(str2);
- }
-
- //运算符入栈
- public void OperatorToStack(String str)
- {
- if(StackOperator.isEmpty()) //判断栈是否为空
- StackOperator.push(str);
- else if("(".equals(str)) //判断传入的运算符是否为"("
- StackOperator.push(str);
- else if(")".equals(str)) //判断传入的运算符是否为")"
- {
- String string;
- while(!"(".equals(string=StackOperator.pop())) //将"("和")"之间的操作符存放到ListExpression中
- ListExpression.add(string);
- }
- else if("(".equals(StackOperator.peek())) //若栈顶元素为(,运算符直接入栈
- StackOperator.push(str);
- else if(ComparePriority(str,StackOperator.peek()))//若str优先级大于栈顶元素则入栈
- StackOperator.push(str);
- else if(!ComparePriority(str,StackOperator.peek()))//若小于则将栈顶元素弹出,str与下一个元素比较
- {
- ListExpression.add(StackOperator.pop());
- OperatorToStack(str);
- }
- }
-
-
- //中缀表达式转换成后缀表达式
- public void ListPreExpressionToListExpression()
- {
- for(String str:ListPreExpression) //遍历ListPreExpression,运算符加入OperatorToStack,数字加入ListExpression
- {
- if(isOperator(str))
- OperatorToStack(str);
- else
- ListExpression.add(str);
- }
-
- //遍历完原始表达式后,将StackOperator栈内的运算符全部添加到ListExpression中
- while(!StackOperator.isEmpty())
- {
- ListExpression.add(StackOperator.pop());
- }
- }
-
-
- //计算方法
-
- //双目运算
- public int open=0;//用于判断输入是否正确
- public double Operation2(String str1,String str2,String str3)
- {
- double num1,num2;
- num2=Double.valueOf(str1).doubleValue();
- num1=Double.valueOf(str2).doubleValue();
- if(str3.equals("+"))
- return num1+num2;
- else if(str3.equals("-"))
- return num1-num2;
- else if(str3.equals("*"))
- return num1*num2;
- else
- {
- if(num2==0) //除数为零时,open=1,后面会对open=1进行输出“illegal”。
- open=1;
- return num1/num2;
- }
- }
-
- //单目运算
- public double Operation1(String str1,String str2)
- {
- double num1;
- num1=Double.valueOf(str1).doubleValue();
- if(str2.equals("tan"))
- {
- if(num1==90) //tan(90)不存在,open=2,其后的代码会输出“non-existent!"
- open=2;
- return 1;
- }
- else if(str2.equals("sin"))
- return Math.sin(num1);
- else if(str2.equals("cos"))
- return Math.cos(num1);
- else
- return Math.log(num1);
-
- }
-
- //计算逆波兰表达式
- public String Opera_ListExpr()
- {
- int open2=0; //用于判断输入是否正确
- for(String str:ListExpression)
- {
- if(str.equals("(")||str.equals(")")) //若ListExpression中含有括号,则报错
- open2=1;
- else if(!isOperator(str)) //把数字存放进运算栈中
- StackOperation.push(str);
- else if("tansincoslog".indexOf(str)>=0) //tan、sin、cos、log进行单目运算
- StackOperation.push(String.valueOf(Operation1(StackOperation.pop(),str)));
- else
- //其它运算符进行双目运算
- StackOperation.push(String.valueOf(Operation2(StackOperation.pop(),StackOperation.pop(),str)));
- }
- if(open==1||open2==1)
- {
- open=0;
- return "illegal!";
- }
- else if(open==2)
- {
- open=0;
- return "non-existent!";
- }
- else
- return StackOperation.pop();
- }
-
-
- public static void main(String[] args)
- {
-
- }
- }
希望能够帮到各位,也欢迎各位给我提提建议,谢谢啦~
链接:https://pan.baidu.com/s/1M8Bfi1K7KhOP5ZNitK-N3g
提取码:kbbe
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。