当前位置:   article > 正文

计算器——Java实现_java实现计算器

java实现计算器

目录

前言

实验要求:

​编辑 界面效果:

 实现计算器类与方法:


前言

为完成数据结构实训课作业,而写的计算器。

实验要求:

 界面效果:

 实现计算器类与方法:

该计算器主要由三大类实现:Calculator,Calculate,以及Stack(老师要求自己写一个数据结构类型(我使用是链式存储));

Calculator类:我主要实现了界面的组件的定义,组合,以及添加事件监听器,以及AC,BaskSpace0,1,2等实现相关组件功能的实现。

代码实现:

  1. import javax.swing.*;
  2. import java.awt.*;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. public class Calculator {
  6. //定义基本组件
  7. JFrame frame=new JFrame("计算器");
  8. JPanel p1=new JPanel();
  9. JPanel p2=new JPanel();
  10. JPanel p3=new JPanel();
  11. TextArea ta=new TextArea(3,40);
  12. TextArea showTa=new TextArea("历史记录\n",14,20);
  13. //组装组件,并添加对应方法
  14. public void init() {
  15. //添加组件
  16. p1.add(ta);
  17. p3.add(showTa);
  18. p2.setLayout(new GridLayout(5,4,4,4));
  19. ActionListener actionListener=new ActionListener() {
  20. @Override
  21. public void actionPerformed(ActionEvent e) {
  22. String command=e.getActionCommand();
  23. ta.append(command);
  24. }
  25. };
  26. p2.add(new JButton(new AbstractAction("AC") {
  27. @Override
  28. public void actionPerformed(ActionEvent e) {
  29. ta.setText("");
  30. }
  31. }));//清空(计算器显示屏中的内容)
  32. p2.add(new JButton(new AbstractAction("BackSpace") {
  33. @Override
  34. public void actionPerformed(ActionEvent e) {
  35. String s=ta.getText();
  36. //如果ta中字符串长度不为0,则可以进行回撤;
  37. if(s.length()!=0){
  38. ta.setText(s.substring(0,s.length()-1));
  39. }
  40. }
  41. }));
  42. p2.add(actionBtn(new JButton("("),actionListener));
  43. p2.add(actionBtn(new JButton(")"),actionListener));
  44. for (int i = 7; i < 10; i++) {
  45. p2.add(actionBtn(new JButton(i+""),actionListener));
  46. }
  47. p2.add(actionBtn(new JButton("+"),actionListener));
  48. for(int i=4;i<=6;i++){
  49. p2.add(actionBtn(new JButton(i+""),actionListener));
  50. }
  51. p2.add(actionBtn(new JButton("-"),actionListener));
  52. for (int i=1;i<=3;i++){
  53. p2.add(actionBtn(new JButton(""+i),actionListener));
  54. }
  55. p2.add(actionBtn(new JButton("x"),actionListener));
  56. p2.add(actionBtn(new JButton("."),actionListener));
  57. p2.add(actionBtn(new JButton("0"),actionListener));
  58. p2.add(actionBtn(new JButton("/"),actionListener));
  59. JButton btn_equal=new JButton(new AbstractAction("=") {
  60. @Override
  61. public void actionPerformed(ActionEvent e) {
  62. String s=ta.getText();
  63. Calculate calculate=new Calculate();
  64. String result=calculate.evaluate(s);
  65. showTa.append(s+"="+result+"\n");
  66. ta.setText(result);
  67. }
  68. });
  69. //窗口内组件布局的设置
  70. p2.add(btn_equal);
  71. Box left_box=Box.createVerticalBox();
  72. left_box.add(p1);
  73. left_box.add(p2);
  74. Box box=Box.createHorizontalBox();
  75. box.add(left_box);
  76. box.add(p3);
  77. frame.add(box);
  78. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭计算器窗口
  79. frame.pack();//设置窗口合适的大小
  80. frame.setVisible(true);//显示窗口
  81. }
  82. public static void main(String[] args) {
  83. // TODO 自动生成的方法存根
  84. //调用init()方法
  85. new Calculator().init();
  86. }
  87. //给按钮添加事件监听器
  88. public JButton actionBtn(JButton btn,ActionListener actionListener){
  89. btn.addActionListener(actionListener);
  90. return btn;
  91. }
  92. }

Calculate类:本类也是代码最核心的地方,主要实现本项目最核心的部分,里面包含很多逻辑关系,利用栈的思想,实现计算器+,-,x,/,=,以及带有小数点,负数,与()(括号)等实现。代码中有很多值得被考虑:如:优先级问题,除法分母不为0等问题。都值得大家慢慢体会!!

代码实现: 

  1. import java.math.BigDecimal;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. //import java.util.Stack;
  5. public class Calculate {
  6. public String evaluate(String express) {
  7. String expression = express;
  8. double calculate = 0;
  9. try {
  10. List<String> infixExpression = depositList(expression);//中缀表达式
  11. List<String> calculateExpression = parsExpression(infixExpression);//后缀表达式
  12. calculate = calculate(calculateExpression);
  13. }catch (RuntimeException e){
  14. return "error";
  15. }
  16. if (calculate==0){
  17. return "0";
  18. } else {
  19. BigDecimal bigDecimal = new BigDecimal(String.format("%.12f",calculate));//去掉前面多余的零
  20. String result = bigDecimal.toString();
  21. if(result.indexOf(".")>0){
  22. result = result.replaceAll("0+?$","");//去掉后面无用的零
  23. result = result.replaceAll("[.]$","");//如小数点后面全是零去掉小数点
  24. }
  25. return result;
  26. }
  27. }
  28. public static List<String> parsExpression(List<String> list) {//方法:将得到的中缀表达式对应的转换后缀表达式对应的List
  29. //定义两个栈
  30. Stack<String> s1 = new Stack<String>(); // 符号栈
  31. List<String> s2 = new ArrayList<String>(); // 储存中间结果的Lists2
  32. for(String item: list ) {
  33. if(item.matches("^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|[1-9]\\d*|0|-[1-9]\\d*\\.\\d*|-0\\.\\d*|-[1-9]\\d*$")) {//如果是一个数加入s2
  34. s2.add(item);
  35. } else if (item.equals("(")) {
  36. s1.push(item);
  37. } else if (item.equals(")")) {
  38. while(!s1.peek().equals("(")) {//如果是右括号“)”,则依次弹出s1栈顶的运算符,并压入s2,直到遇到左括号为止,此时将这一对括号丢弃
  39. s2.add(s1.pop());
  40. }
  41. s1.pop();//将 ( 弹出 s1栈, 消除小括号
  42. } else {
  43. while(s1.size() != 0 && operation.getValue(s1.peek()) >= operation.getValue(item) ) {
  44. s2.add(s1.pop());
  45. }
  46. s1.push(item);
  47. }
  48. }
  49. while(s1.size() != 0) { //将s1中剩余的运算符依次弹出并加入s2
  50. s2.add(s1.pop());
  51. }
  52. return s2;
  53. }
  54. public static List<String> depositList(String s) {
  55. List<String> list = new ArrayList<String>();//定义一个List,存放中缀表达式 对应的内容
  56. int i = 0;
  57. String str;
  58. char c;
  59. do {
  60. boolean isMinus = false;
  61. if ((c=s.charAt(i))=='-'){
  62. if (i==0 || s.charAt(i-1)=='('){
  63. isMinus=true;
  64. }
  65. }
  66. if(((c=s.charAt(i)) < 48 || (c=s.charAt(i)) > 57) && !isMinus) {
  67. list.add("" + c);
  68. i++;
  69. } else {
  70. str = ""; //先将str 置成"" '0'[48]->'9'[57]
  71. do {
  72. str += c;
  73. i++;
  74. }while(i < s.length() && (((c=s.charAt(i)) >= 48 && (c=s.charAt(i)) <= 57) || (c=s.charAt(i)) == '.'));
  75. list.add(str);
  76. }
  77. }while(i < s.length());
  78. return list;
  79. }
  80. public static double calculate(List<String> list) {
  81. Stack<String> stack = new Stack<String>();// 创建栈
  82. for (String item : list) {
  83. if (item.matches("^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|[1-9]\\d*|0|-[1-9]\\d*\\.\\d*|-0\\.\\d*|-[1-9]\\d*$")) { //使用正则表达式匹配多位数
  84. stack.push(item);
  85. } else {
  86. double num2 = Double.parseDouble(stack.pop()); // pop出两个数,并运算, 再入栈,如果空就赋值为零是为了让负数也能算
  87. double num1 = Double.parseDouble(stack.pop());
  88. double res = 0;
  89. if (item.equals("+")) {
  90. res = num1 + num2;
  91. } else if (item.equals("-")) {
  92. res = num1 - num2;
  93. } else if (item.equals("x")) {
  94. res = num1 * num2;
  95. } else if (item.equals("/")&&num2!=0) {
  96. res = num1 / num2;
  97. } else {
  98. throw new RuntimeException("运算符有误");
  99. }
  100. stack.push("" + res);
  101. }
  102. }
  103. return Double.parseDouble(stack.pop());
  104. }
  105. }
  106. //编写一个类 Operation 可以返回一个运算符 对应的优先级
  107. class operation {
  108. private static int Add = 1;
  109. private static int Sub = 1;
  110. private static int Mul = 2;
  111. private static int Div = 2;
  112. //写一个方法,返回对应的优先级数字
  113. public static int getValue(String operation) {
  114. int result = 0;
  115. switch (operation) {
  116. case "+":
  117. result = Add;
  118. break;
  119. case "-":
  120. result = Sub;
  121. break;
  122. case "x":
  123. result = Mul;
  124. break;
  125. case "/":
  126. result = Div;
  127. break;
  128. default:
  129. break;
  130. }
  131. return result;
  132. }
  133. }

 Stack类:该类是最底层的东西,主要通过结点链式存储方法写出的类,该类在Java.util包下就已经有该方法的实现,但在这我本人是为了完成老师的要求,才加上去的。

代码实现:

  1. public class Stack<T> {
  2. //记录首结点
  3. private Node head;
  4. //栈中元素的个数
  5. private int N;
  6. public Stack() {
  7. head = new Node(null, null);
  8. N = 0;
  9. }
  10. //判断当前栈中元素个数是否为0
  11. public boolean isEmpty() {
  12. return N == 0;
  13. }
  14. //把t元素压入栈
  15. public void push(T t) {
  16. Node oldNext = head.next;
  17. Node node = new Node(t, oldNext);
  18. head.next = node;
  19. //个数+1
  20. N++;
  21. }
  22. //弹出栈顶元素
  23. public T pop() {
  24. Node oldNext = head.next;
  25. if (oldNext == null) {
  26. return null;
  27. }
  28. //删除首个元素
  29. head.next = head.next.next;
  30. //个数-1
  31. N--;
  32. return oldNext.item;
  33. }
  34. public T peek(){
  35. if(!isEmpty()){
  36. return head.next.item;
  37. }
  38. return null;
  39. }
  40. //获取栈中元素的个数
  41. public int size() {
  42. return N;
  43. }
  44. private class Node {
  45. public T item;
  46. public Node next;
  47. public Node(T item, Node next) {
  48. this.item = item;
  49. this.next = next;
  50. }
  51. }
  52. }

这篇文章到这也达到尾声了,谢谢大家阅览!最后也希望大家能够试试这计算器的功能,帮我检验它是否存在bug,如果有的话,请留言,我看到之后就一定修改。

冬天到了,春天还会远吗?

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/275808?site
推荐阅读
相关标签
  

闽ICP备14008679号