java的复杂四则运算,暂时先实现四则运算表达式的解析。存储入数据栈、运算符栈。
View Code
1 package com.app;
2
3 import java.util.Stack;
4
5 public class calcapp {
6 private Stack<Double> s1;
7 private Stack<Character> s2;
8
9 public calcapp(){
10 s1 = new Stack<Double>();
11 s2 = new Stack<Character>();
12 }
13
14 public void calcformula(String input){
15
16 //先实现对四则运算表达式的解析
17 char temp;
18 StringBuffer sv = new StringBuffer();
19 Double dv = 0.0;
20
21 for(int i = 0; i < input.length(); i++){
22 temp = input.charAt(i);
23
24 if(('=' == temp)
25 && (0 != sv.length())){
26 dv = Double.parseDouble(sv.toString());
27 s1.push(dv);
28 }
29
30 if(' ' == temp){
31 continue;
32 }
33
34 if(isOperator(temp)){
35 if(0 != sv.length()){
36 dv = Double.parseDouble(sv.toString());
37 sv.setLength(0);
38 s1.push(dv);
39 dv = 0.0;
40 }
41
42 s2.push(temp);
43 }else{
44 sv.append(temp);
45 }
46 }// end of for(int i = 0; i < input.length(); i++){
47
48 //show the Operataror
49 System.out.println("number as following:");
50 while(!s1.empty()){
51 System.out.println(s1.pop());
52 }
53 System.out.println("Operator as following:");
54 while(!s2.empty()){
55 System.out.println(s2.pop());
56 }
57 }
58
59
60 public boolean isOperator(char temp){
61 if(('(' == temp)
62 ||(')' == temp)
63 ||('+' == temp)
64 ||('-' == temp)
65 ||('*' == temp)
66 ||('/' == temp)){
67 return true;
68 }
69
70
71 return false;
72 }
73 }