代码是先看了 http://blog.csdn.net/whos2002110/article/details/19119449
这个网址的。然后 自己记忆写了一份。
本来目的是要学一些 解释器的。虽然也看到一些实现,但是感觉对我有点难度,于是从简单开始学习。
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class CaSame {
public List<String> toString(String ss) {
List<String> result = new ArrayList<String>();
String num = "";
for (int i = 0; i < ss.length(); i++) {
if (Character.isDigit(ss.charAt(i)))
num = num + ss.charAt(i);
else {
if (num != "") {
result.add(num);
num = "";
}
result.add(String.valueOf(ss.charAt(i)));
}
}
if (num != "")
result.add(num);
return result;
}
public List<String> Change(List<String> first) {
Stack<String> stack = new Stack<String>();
List<String> result = new ArrayList<String>();
for (int i = 0; i < first.size(); i++) {
String temp = first.get(i);
char tc = temp.charAt(0);
if (Character.isDigit(tc)) {
result.add(temp);
} else {
if ("(".equals(temp)) {
stack.push(temp);
} else if (")".equals(temp)) {
while (!stack.isEmpty() && !stack.peek().equals( "(")) {
result.add(stack.pop());
}
if(!stack.isEmpty())
stack.pop();
} else {
if (!stack.isEmpty() && compare(stack.peek().charAt(0), tc)) {
result.add(stack.pop());
}
stack.push(temp);
}
}
}
while(!stack.isEmpty())
result.add(stack.pop());
return result;
}
public String Computer(List<String> result) {
Stack<String> stack = new Stack<String>();
for(int i=0;i<result.size();i++){
char c = result.get(i).charAt(0);
if(Character.isDigit(c)){
stack.push(result.get(i));
}else{
int b = Integer.parseInt(stack.pop());
int a= Integer.parseInt(stack.pop());
int r = 0;
switch(c){
case '+':
r = a+b ;
break;
case '-':
r = a-b ;
break;
case '*':
r = a*b ;
break;
case '/':
r = a/b ;
break;
}
stack.push(String.valueOf(r));
}
}
return stack.peek();
}
public Boolean compare(char a, char b) {
char c[] = { '+', '-' };
char d[] = { '*', '/' };
if (in(a, d) && (in(b, c) || in(b, d)))
return true;
if (in(a, c) && in(b, c))
return true;
return false;
}
public Boolean in(char a, char[] b) {
for (int i = 0; i < b.length; i++) {
if (a == b[i])
return true;
}
return false;
}
public static void main(String[] args) {
CaSame cs = new CaSame();
List<String> frist = cs.toString("(23-24)*12)");
// System.out.println(cs.compare('+', '*'));
frist = cs.Change(frist);
for (int i = 0; i < frist.size(); i++) {
System.out.print(frist.get(i));
}
System.out.println();
String result = cs.Computer(frist);
System.out.println(result);
}
}
整个过程包括,转换, 更改顺序,计算。