这是编译原理课上的一个实验,要将输入的表达式转换成后缀表达式,然后进行计算。当时写的程序有错误,改了两天,没有了错误,但还是有些表达式计算不出正确的结果,实在不想改了,等什么时候心情好了,再看看吧。
由这段代码我学到:不要着急动手,动手之前,要考虑周全,这样才会更快。
代码如下:
package net.mindview.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
public class Site {
Stack<Character> stack2 = new Stack<Character>();
public void show() {
Stack<Character> stack1 = new Stack<Character>();
List<Character> list = new ArrayList<Character>();
Scanner in = new Scanner(System.in);
String s = in.next();
char ch;
char top;
for(int i = 0; i < s.length(); i++) {
ch = s.charAt(i);
list.add(ch);
}
System.out.println("原表达式为:");
for(int m = 0; m < list.size(); m++) {
System.out.print(list.get(m));
}
int i = 0;
ch = list.get(0);
while(list.get(i) != '#') {
ch = list.get(i);
switch(ch) {
case '(':
stack1.add(ch);i++;break;
case ')':
while(stack1.peek() != '(') {
top = stack1.pop();
stack2.add(top);
}
stack1.pop();
i++;break;
case '+':
case '-':
while(!stack1.empty() && stack1.peek() != '(') {
top = stack1.pop();
stack2.add(top);
}
stack1.add(ch);i++;
break;
case '*':
case '/':
while(!stack1.empty()) {
if(stack1.peek() == '*' ||
stack1.peek() == '/') {
top = stack1.pop();
stack2.add(top);
}
}
stack1.add(ch);i++;break;
case ' ':
i++;
break;
default:
while(ch >= '0' && ch <= '9'&& i < list.size()) {
stack2.add(ch);
i += 1;
ch = list.get(i);
}
stack2.add('#');
}//end of switch
}//end of for
for(int j = 0; j < stack1.size(); j++) {
top = stack1.pop();
stack2.add(top);
}
stack2.add('#');
System.out.println("生成的后缀表达式为:");
for(int k = 0; k < stack2.size(); k++) {
System.out.print(stack2.get(k));
}
}
public void Result() {
Stack<Double> res = new Stack<Double>();
int j = 0;
char ch = stack2.get(j);
double a = 0,b = 0,result = 0;
while(stack2.get(j) != '#') {
if(j < stack2.size())
ch = stack2.get(j);
switch(ch) {
case '+':
a = res.pop();
b = res.pop();
result = b + a;
res.add(result);
j++;
break;
case '-':
a = res.pop();
b = res.pop();
result = b - a;
res.add(result);
j++;
break;
case '*':
a = res.pop();
b = res.pop();
result = b * a;
res.add(result);
j++;
break;
case '/':
a = res.pop();
b = res.pop();
result = b / a;
res.add(result);
j++;
break;
default:
double d = 0;
while(ch >= '0' && ch <= '9' && ch != '#') {
d = d * 10 + ch - '0';
j++;
ch = stack2.get(j);
}
res.add(d);
if(ch == '#') {
j++;
}
}
}
System.out.println("计算结果为:" + res.peek());
}
public static void main(String[] args) {
Site site = new Site();
site.show();
site.Result();
}
}
输入:
(12+2)/2#
运行结果为:
原表达式为:
(12+2)/2#生成的后缀表达式为:
12#2#+2#/#计算结果为:7.0
显示结果是正确的
但是输入:
(12+2)*2#
运行结果为:
原表达式为:
(12+2)*2#生成的后缀表达式为:
12#2#+2#*#计算结果为:28.0