设为首页 加入收藏

TOP

200 行 Java 代码搞定计算器程序(二)
2018-01-11 06:06:46 】 浏览:419
Tags:200 Java 代码 搞定 计算器 程序
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(); } 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); } }
首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇改善代码可测性的若干技巧 下一篇杂谈 GC

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目