浏览 3038 次
锁定老帖子 主题:用Applet实现表达式求值
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2007-03-12
=======================ExpressionModel=================== /* *这个就是表达式的模型组件了,它的三个属性,分别代表了它的中则表达式和右则表达式 *而那两个属性分别是输入的式子和得到的结果 */ package expression; import java.text.*; import java.util.*; public class ExpressionModel extends Observable { private ArrayList<String> middle; private ArrayList<String> right; private String input, result; public ExpressionModel() { middle = new ArrayList<String>(); right = new ArrayList<String>(); } //判断一个字符是不是操作符 private boolean isOperator( String op ) { if( op.equals("+") || op.equals("-") || op.equals("%") ||op.equals("*")|| op.equals("/") || op.equals("(") ||op.equals(")") ) return true; else return false; } //得到一个操作符的优先级 private int priority( String op ) { if( op.equals("+") || op.equals("-") || op.equals("(") ) return 1; else if( op.equals("*") || op.equals("/") || op.equals("%") ) return 2; else return 0; } //计算两个数和一个运算符得到的结果 private String calTwoNumber( String op, String a, String b ) throws Exception { double x = Double.parseDouble( b ); double y = Double.parseDouble( a ); double z = 0; if( op.equals("+") ) z = x + y; else if( op.equals("-") ) z = x - y; else if( op.equals("*") ) z = x * y; else if( op.equals("/") ) z = x / y; else if( op.equals("%") ) z = x % y; else z=0; return Double.toString( z ); } //将我们输入的中则表达式转换成逆波兰式 private void turnToRight() { MyStack stack = new MyStack(); String op; int pos = 0; StringTokenizer st = new StringTokenizer(input,"+-*/%()",true); while( st.hasMoreElements() ) middle.add( st.nextToken() ); while(true) { if( isOperator( middle.get(pos) ) ) { if( stack.getTop() == -1 || (middle.get(pos)).equals("(") ) { stack.push( middle.get(pos) ); } else { if( (middle.get(pos)).equals(")") ) { if( !(stack.top()).equals("(") ) { op = stack.pop(); right.add(op); } } else { if( priority(middle.get(pos)) <= priority(stack.top()) && stack.getTop() != -1 ) { op = stack.pop(); if( !op.equals("(") ) right.add(op); } stack.push( middle.get(pos) ); } } } else right.add( middle.get(pos) ); pos++; if( pos >= middle.size() ) break; } while( stack.getTop() != -1 ) { op = stack.pop(); right.add(op); } } private void calculate( String expression ) throws Exception { input = expression; turnToRight(); MyStack stack = new MyStack(); String op1, op2, is = null; Iterator<String> it = right.iterator(); while(it.hasNext()) { is = it.next(); if( isOperator(is) ) { op1 = stack.pop(); op2 = stack.pop(); stack.push( calTwoNumber(is,op1,op2) ); } else stack.push(is); } NumberFormat form = NumberFormat.getInstance(); form.setMaximumFractionDigits(5); result = input + "=" + form.format( Double.parseDouble( stack.pop() ) ); setChanged(); notifyObservers(); } public void input(String expression) throws Exception { calculate(expression); middle.clear(); right.clear(); } public String getResult(){ return result; } } ===============MyStack============== //我们用到的自己的堆栈 package expression; import java.util.*; public class MyStack { private LinkedList<String> list; private int top; public MyStack() { list = new LinkedList<String>(); top = -1; } public void push(String value) { top++; list.addFirst(value); } public String pop() { String temp = list.getFirst(); top--; list.removeFirst(); return temp; } public String top() { return list.getFirst(); } public int getTop() { return top; } } ===============ExpressionController========------ //控制器组件,包括一个输入域和两个按纽 package expression; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ExpressionController extends JPanel { private ExpressionModel expressionModel; private JTextField calTextField; public ExpressionController( ExpressionModel controllerModel ) { super(); expressionModel = controllerModel; calTextField = new JTextField( 15 ); JButton calButton = new JButton( "计算" ); JButton delButton = new JButton( "取消" ); calButton.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent event ) { try { expressionModel.input( calTextField.getText() ); calTextField.setText(""); } catch ( Exception exception ) { JOptionPane.showMessageDialog ( ExpressionController.this, "请输入有效表达式!", "错误", JOptionPane.ERROR_MESSAGE ); calTextField.setText(""); } } } ); delButton.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent event ) { try { calTextField.setText(""); } catch ( Exception exception ) { calTextField.setText(""); } } } ); setLayout( new FlowLayout() ); add( calTextField ); add( calButton ); add( delButton ); } public Dimension getPreferredSize() { return new Dimension( 320, 40 ); } public Dimension getMinimumSize() { return getPreferredSize(); } public Dimension getMaximumSize() { return getPreferredSize(); } } ================ExpressionView ================== //用来显示结果的视图 package expression; import java.awt.*; import java.text.*; import java.util.*; import javax.swing.*; import javax.swing.border.*; public class ExpressionView extends JPanel implements Observer { private ExpressionModel expressionModel; private JLabel display = new JLabel(); public ExpressionView( ExpressionModel model ) { if( model == null ) throw new NullPointerException(); expressionModel = model; expressionModel.addObserver( this ); add( display ); setBackground( Color.white ); setBorder( new MatteBorder( 1, 1, 1, 1, Color.black ) ); } public void update( Observable observable, Object object ) { display.setText( expressionModel.getResult() ); } public Dimension getPreferredSize() { return new Dimension( 320, 60 ); } public Dimension getMinimumSize() { return getPreferredSize(); } public Dimension getMaximumSize() { return getPreferredSize(); } } ===================Expression===================== //最后把这些组装到这里吧 package expression; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; public class Expression extends JApplet { public void init() { ExpressionModel model = new ExpressionModel(); ExpressionView view = new ExpressionView( model ); ExpressionController controller = new ExpressionController( model ); Container contentPane = getContentPane(); contentPane.add( view, BorderLayout.CENTER ); contentPane.add( controller, BorderLayout.SOUTH ); setSize( 320, 100 ); } } 把这几个类打包到一个jar文件后,再创建个htm文件来访问它 <object classid = "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" codebase = "http://java.sun.com/update/1.5.0/jinstall-1_5-windows-i586.cab#Version=5,0,0,5" WIDTH = 320 HEIGHT = 100 > <PARAM NAME = CODE VALUE = "expression.Expression" > <PARAM NAME = ARCHIVE VALUE = "expression.jar" > <param name = "type" value = "application/x-java-applet;version=1.5"> <param name = "scriptable" value = "false"> </object> 这样就行了,不过你的机器需要安装jre 5 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2007-03-12
楼主,编辑下,用code标签
|
|
返回顶楼 | |
发表时间:2007-03-12
呵呵,不好意思噢
|
|
返回顶楼 | |