方法:
1.将string类型的表达式输入转换成后缀表达式
2.计算后缀表达式
步骤一:将string类型的表达式输入转换成后缀表达式
输入字符串表达式,并将表达式转换成char型数组
String a = "(5+5)*2-(4-2)/2";
char [] x = a.toCharArray();
Stack<Character> b = new Stack<>();
String back = "";//后缀表达式
后缀表达式实现
1. 遇到”(“时进栈
2. 遇到数字,将数字加入back字符串后面
3. 遇到”+“、”-“、”*“、”/“时,判断栈顶元素的优先级是否高于或等于该元素,如果是则依次出栈加入back直到栈顶元素优先级小于该元素,该元素进栈
4. 遇到”)“时,栈顶元素依次出栈直到栈顶为”(“,删除栈顶”(“元素
for (int i = 0; i <x.length; i++) {
//System.out.println(back);
if(x[i] == '(') b.push(x[i]);
if(x[i] == '+' || x[i] == '-') {
while(!b.isEmpty() && (b.peek() == '*' || b.peek() == '/')) {
back = back + b.peek();
b.pop();
}
b.push(x[i]);
}
if(x[i] == '*' || x[i] == '/') {
while(!b.isEmpty() && (b.peek() == '*' || b.peek() == '/')) {
back = back + b.peek();
b.pop();
}
b.push(x[i]);
}
if(x[i] == ')') {
while (!b.isEmpty()){
if(b.peek() == '(') {b.pop(); break;}
//System.out.println(back);
back = back + b.peek();
b.pop();
}
}
if(x[i] >= '0' && x[i] <= '9') back = back + x[i];
}
while(!b.isEmpty()){
back += b.peek();
b.pop();
}
System.out.println(back);
步骤二:计算后缀表达式
1. 遇到数字则进栈
2. 遇到运算符时,取出栈顶两个元素进行计算
3. 直到栈为空
Stack<Double> bb = new Stack<>();
double p,q;
char [] xx = back.toCharArray();
for (int i = 0; i < xx.length; i++) {
if(xx[i] >= '0' && xx[i] <= '9') {
double s = (double) xx[i] - 48;
//System.out.println(s);
bb.push(s);
//System.out.println(xx[i] - 48);
}
if(xx[i] == '+'){
p = bb.peek();
bb.pop();
q = bb.peek();
bb.pop();
double result = p+q;
bb.push(result);
//System.out.println(result);
}
if(xx[i] == '-'){
p = bb.peek();
bb.pop();
q = bb.peek();
bb.pop();
double result = q-p;
bb.push(result);
//System.out.println(result);
}
if(xx[i] == '*'){
p = bb.peek();
bb.pop();
q = bb.peek();
bb.pop();
double result = p*q;
bb.push(result);
//System.out.println(result);
}
if(xx[i] == '/'){
p = bb.peek();
bb.pop();
q = bb.peek();
bb.pop();
double result = q/p;
bb.push(result);
//System.out.println(result);
}
}
int aaa = bb.peek().intValue();
System.out.println(aaa);
优势与局限
1. 该方法解决了优先级高无括号的问题
2. 该方法解决了除法生成小数的问题
3. 该方法仅限于0-9的简单计算
4. 该方法输入仅限于整数