200行Java代码编写一个计算器程序
程序员文章站
2023-12-16 08:37:46
发现了大学时候写的计算器小程序,还有个图形界面,能够图形化展示表达式语法树,哈哈;)
只有200行java代码,不但能够计算加减乘除,还能够匹配小括号~
代码点评:...
发现了大学时候写的计算器小程序,还有个图形界面,能够图形化展示表达式语法树,哈哈;)
只有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>(); publicstaticvoidmain(string[] args) { calcgui gui = new calcgui(); gui.usergui(); } publicvoidusergui(){ this.setlayout(new borderlayout()); textfield tf = new textfield("请输入表达式,按enter开始计算~", 40); tf.selectall(); tf.gettext(); tf.addkeylistener(new keyadapter(){ publicvoidkeypressed(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; publicvoidpaint(graphics g){ super.paint(g); if(calcsuccess){ if(resulttree != null){ g.drawstring("计算结果为:" + resulttree.value, 10, 80); int rootbeginx = this.getwidth() / 2; int rootbeginy = 100; point p = new point(rootbeginx, rootbeginy); drawtree(g, resulttree, p, this.getwidth() / 2 - 20, p); } }else{ g.setcolor(color.red); g.drawstring("表达式语法有误!", 10, 80); } } privatevoiddrawcircle(graphics g, point p, int r){ g.drawoval(p.x - r, p.y - r, r * 2, r * 2); } privatevoiddrawtree(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); }else{ 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)); }else if(instr.charat(i) == ' '){ i++; continue; }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(); } privatedoubledooperate(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); } } privateintgetsub(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(); } privatevoidout(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代码编写一个计算器程序,希望对大家有所帮助