类实现
import java.util.Scanner;
public class Expression {
public Expression(){}
public Expression(String str){
this.str = str + "#";
}
public int Compute(){
int[] OPND = new int[100];//运算对象栈
char[] OPTR = new char[100];//运算符栈
OPTR[0] = '#';
int top1 = -1;
int top2 = 0;//当前符号栈内存放着'#'
int i,k,x,y,z = 0;
char op;
Scanner scan = new Scanner(str);
for(i = 0; i<str.length();){
if(str.charAt(i) >= 48 && str.charAt(i) <= 57){
OPND[++top1] = str.charAt(i++) - 48;//数字直接入栈
}
else{
k = this.Comp(str.charAt(i), OPTR[top2]);
if(k == 1){
OPTR[++top2] = str.charAt(i++);
}
else if(k == -1){
y = OPND[top1--];
x = OPND[top1--];
op = OPTR[top2--];
switch(op){
case '+':z = x + y;break;
case '-':z = x - y;break;
case '*':z = x * y;break;
case '/':z = x / y;break;
}
OPND[++top1] = z;
}
else if(k == 0){
top2--;
i++;
}
}
}
return OPND[top1];
}
private int Comp(char str1,char str2){//1 str1优先 0 优先级相等 -1 str2优先
switch(str1){
case '+':
case '-':
if(str2 == '(' || str2 == '#')
return 1;
else
return -1;
case '*':
case '/':
if(str2 == '*' || str2 == '/')
return -1;
else
return 1;
case '(':
return 1;
case ')':
if(str2 == '(')
return 0;
else
return -1;
case '#':
if(str2 == '#')
return 0;
else
return -1;
default:
break;
}
return 2;
}
private String str;
}
主方法的调用
import java.util.Scanner;
public class Shujvjiegou {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("请输入一个表达式");
String str = scan.next();
Expression ex = new Expression(str);
System.out.println("表达式的值是:" + ex.Compute());
scan.close();
}
}
效果预览