English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
대학 시절에 썼던 계산기 소프트웨어小程序을 발견했는데, 그래픽 인터페이스도 있어서 표현식 문법 트리를 그래픽으로 표시할 수 있습니다. 하하;)
그리고200 행의 Java 코드는 덧셈, 뺄셈, 곱셈, 나눗셈을 계산할 뿐만 아니라 소괄호를 일치시킬 수도 있습니다.
코드 평가:
평범한 인터페이스配色에서 단순하고 이해하기 쉬운 오류 표시까지 모두 "사용자 경험"을 최우선으로 한 설계 이념을 반영하고 있습니다; 코드의 이상 처리는 전면적으로 합리적이며, 차가운 눈에 띄지 않습니다. 코드 인덱싱은 우아하고 화려하며, 변수 이름은 직관적이고 이해하기 쉽습니다. 또한 길이가 적절하고 명확한 설명을 결합하여, 프로그램 전체는 청신한 느낌을 줍니다. 작가의 학습에 대한 사랑과 설계에 대한 철저함을 배경에서 볼 수 있으며, 기술자 정신이 보여지며, 실제로는 대학 데이터 구조를 응용한 모범입니다!
구현 코드는 다음과 같습니다:
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; /** * 그래픽 인터페이스 계산기 프로그램은 덧셈, 뺄셈, 곱셈, 나눗셈만 계산할 수 있습니다. * 계산식에 소괄호가 포함될 수 있습니다. 숫자는 소수점이 될 수 있습니다. */ 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("请输入表达式,按Enter开始计算~", 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("계산 결과는:", + 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("표현식 문법이 오류입니다!", 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 + , width / 2, pme); drawTree(g, node.rt, new Point(pme.x + width / 2, pme.y + , 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) == '.')) nodesStack.push(new TreeNode(number));++)); else if(inStr.charAt(i) == ' '){ } continue; i++; else{ }// operation char op = inStr.charAt(i); int subNew = getSub(op); boolean goOn = true; while(goOn){ if(opsStack.isEmpty()) throw new Exception("运算符太少!"); 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("没有匹配的操作符:" + 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("非法操作符:" + 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); } }
정리
위에 설명한 것은 편집자가 여러분에게 소개한 것입니다.200 행 Java 코드를 사용하여 계산기 프로그램을 작성했습니다. 많은 도움이 되길 바랍니다. 어떤 질문이나 의문이 있으면 댓글을 달아주세요. 편집자는 즉시 답변을 드리겠습니다. 또한, 양해 주셔서 감사합니다. 노래 튜토리얼에 대한 지원에 감사합니다!