English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
found a calculator mini program I wrote in college, with a graphical interface that can graphically display the expression syntax tree, hahaha;)
Only200 lines of Java code, not only can calculate addition, subtraction, multiplication, and division, but also can match parentheses~
Code Review:
From the simple interface color matching to the easy-to-understand error prompts, it fully reflects the design philosophy of 'user experience' first; the code exception handling is comprehensive and reasonable, without any loopholes, the code indentation is elegant and generous, and the variable naming is intuitive and easy to understand; combined with moderate-length and clear comments, the program gives a refreshing and elegant feeling. Behind it, it is not difficult to see the author's love for learning and the strict pursuit of design, a glimpse of the craftsmanship spirit, which can truly be said to be a model of applying university data structure knowledge in practice!
The implementation code is shown as follows:
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Graphics; import java.awt.Point; import java.awt.TextField; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.Stack; import javax.swing.JFrame; /** * This is a graphical interface calculator program, which can only perform addition, subtraction, multiplication, and division, * Parentheses are allowed in the expression. Numbers can be decimal numbers */ public class CalcGUI extends JFrame { private static final long serialVersionUID = 1L; private TreeNode resultTree; private String textFieldString; private boolean calcSuccess = true; private char[][] ops = { {'>', '>', '<', '<', '<', '>', '>'}, {'>', '>', '<', '<', '<', '>', '>'}, {'>', '>', '>', '>', '<', '>', '>'}, {'>', '>', '>', '>', '<', '>', '>'}, {'<', '<', '<', '<', '<', '=', 'E'}, {'E', 'E', 'E', 'E', 'E', 'E', 'E'}, {'<', '<', '<', '<', '<', 'E', '='}, }; Stack<TreeNode> nodesStack = new Stack<TreeNode>(); Stack<Character> opsStack = new Stack<Character>(); public static void main(String[] args) { CalcGUI gui = new CalcGUI(); gui.userGUI(); } public void userGUI() { this.setLayout(new BorderLayout()); TextField tf = new TextField("Please enter the expression, press Enter to start calculation~", 4, 0); tf.selectAll(); tf.getText(); tf.addKeyListener(new KeyAdapter(){ public void keyPressed(KeyEvent e){ if(e.getKeyCode() == KeyEvent.VK_ENTER){ textFieldString = ((TextField)e.getComponent()).getText(); calcSuccess = true; resultTree = null; try{ resultTree = calc(textFieldString + "#\ }catch(Exception e1){ calcSuccess = false; } CalcGUI.this.repaint(); } } }); this.add(tf, BorderLayout.NORTH); this.setSize(500, 500); this.setTitle("calc GUI"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setResizable(true); this.setVisible(true); } private int levelHeight = 60; private int diameter = 25; public void paint(Graphics g){ super.paint(g); if(calcSuccess){ if(resultTree != null){ g.drawString("The calculation result is:", + resultTree.value, 10,} 8, 0); int rootBeginX = this.getWidth() / 2; int rootBeginY = 100; Point p = new Point(rootBeginX, rootBeginY); drawTree(g, resultTree, p, this.getWidth()) / 2 - 20, p); } } g.setColor(Color.RED); g.drawString("The expression syntax is incorrect!", 10,} 8, 0); } } private void drawCircle(Graphics g, Point p, int r){ g.drawOval(p.x - r, p.y - r, r * 2, r * 2); } private void drawTree(Graphics g, TreeNode node, Point pme, int width, Point pfather){ if(node == null) return; // System.out.println("in drawTree, node.value=" + node.value + ",node.op=" + node.op); g.setColor(Color.GREEN); this.drawCircle(g, pme, diameter / 2); g.drawLine(pme.x, pme.y, pfather.x, pfather.y); if(node.op != 'E'){ g.setColor(Color.BLACK); g.drawString(String.valueOf(node.op), pme.x, pme.y); } g.setColor(Color.BLACK); g.drawString(String.valueOf(node.value), pme.x - diameter / 2, pme.y); } drawTree(g, node.lft, new Point(pme.x - width / 2, pme.y + , levelHeight, width / 2, pme); drawTree(g, node.rt, new Point(pme.x + width / 2, pme.y + , levelHeight, width / 2, pme); } public TreeNode calc(String inStr) throws Exception{ opsStack.push('#'); StringBuilder buf = new StringBuilder(); int i = 0; while(i < inStr.length()){ if(Character.isDigit(inStr.charAt(i)) || inStr.charAt(i) == '.'){// number buf.delete(0, buf.length()); while(i < inStr.length() && (Character.isDigit(inStr.charAt(i)) || inStr.charAt(i) == '.')) buf.append(inStr.charAt(i))++)); Double number = Double.parseDouble(buf.toString()); nodesStack.push(new TreeNode(number)); } i++; continue; }// operation char op = inStr.charAt(i); int subNew = getSub(op); boolean goOn = true; while(goOn){ if(opsStack.isEmpty()) throw new Exception("Too few operators!"); char opFormer = opsStack.peek(); int subFormer = getSub(opFormer); switch(ops[subFormer][subNew]){ case '=': goOn = false; opsStack.pop(); break; case '<': goOn = false; opsStack.push(op); break; case '>': goOn = true; TreeNode n1 = nodesStack.pop(); TreeNode n0 = nodesStack.pop(); double rs = doOperate(n0.value, n1.value, opFormer); nodesStack.push(new TreeNode(rs, opFormer, n0, n1)); opsStack.pop(); break; default: throw new Exception("No matching operator:"); + op); } } i++; } } return nodesStack.pop(); } private double doOperate(double n0, double n1, char op) throws Exception{ switch(op){ case '"}}+: return n0 + n1; case '"}}-: return n0 - n1; case '"}}*: return n0 * n1; case '"}}/: return n0 / n1; default: throw new Exception("Illegal operator: "); + op); } } private int getSub(char c){ switch(c){ case '"}}+: return 0; case '"}}-': return 1; case '"}}*': return 2; case '"}}/': return 3; case '(': return 4; case ')': return 5; case '#': return 6; default : return -1; } } } class TreeNode{ public double value; public char op = 'E'; public TreeNode lft; public TreeNode rt; public TreeNode(double value){ this.value = value; } public TreeNode(double value, char op, TreeNode lft, TreeNode rt){ this.value = value; this.op = op; this.lft = lft; this.rt = rt; } StringBuilder buf = new StringBuilder(); public String toString(){ out(this); return buf.toString(); } private void out(TreeNode node){ if(node == null) return; out(node.lft); if(node.op != 'E') buf.append(node.op); else buf.append(node.value); out(node.rt); } }
Summary
The above is what the editor has introduced to everyone2Here is a Java program that writes 00 lines of code to create a calculator, I hope it will be helpful to everyone. If you have any questions, please leave a message, and the editor will reply to everyone in time. I also want to express my sincere gratitude to everyone for supporting the呐喊 tutorial!