200 行 Java 代码搞定计算器程序 您所在的位置:网站首页 java做个计算器代码 200 行 Java 代码搞定计算器程序

200 行 Java 代码搞定计算器程序

#200 行 Java 代码搞定计算器程序| 来源: 网络整理| 查看: 265

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[][] = {

{'>', '>', '', '>', '', '>', '>', '>', '', '>'},

{'>', '>', '>', '>', '', '>'},

{'':

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);

}

}返回搜狐,查看更多



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有