四则运算首先是要明白将中缀表达式转换为后缀表达式,如1、中缀式:(2+6)*8/3 转换为后缀式为:26+8*3/ ;2、中缀式: 2+6*8/3 转换为后缀是为:268*3/+
之后是通过得到的后缀表达式进行计算:遍历后缀表达式,遇到数字存入栈中,遇到操作符,就将栈中的数字弹出进行计算,将计算的结果入栈,如此循环至遍历结束,即得出结果。
代码如下:
import java.util.Stack;
public class Arithmetic {
// 前缀转后缀
public static String suffix(String str) {
String suffix = "";
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch >= '0' && ch <= '9') {
suffix += str.charAt(i);
continue;
}
if (ch == '(') {
stack.push('(');
continue;
}
if (ch == '/' || ch == '*') {
while (!stack.empty() && (stack.peek().equals('/') || stack.peek().equals('*'))) {
suffix += stack.pop();
}
stack.push(ch);
continue;
}
if (ch == '+' || ch == '-') {
while (!stack.empty() && (stack.peek() != '(')) {
suffix += stack.pop();
}
stack.push(ch);
continue;
}
if (ch == ')') {
while (stack.peek() != '(') {
suffix += stack.pop();
}
stack.pop();
}
}
while (!stack.empty()) {
suffix += stack.pop();
}
return suffix;
}
// 计算
public static double caculate(String str) {
String op = suffix(str);
double result = 0;
String range = "0123456789";
Stack<String> stack = new Stack<String>();
for (int i = 0; i < op.length(); i++) {
String item = op.substring(i, i+1);
//此处通过contains方法判断是操作符还是数字
if (range.contains(item)) {
stack.push(item);
} else {
if(item.equals("+")) {
result = Double.parseDouble(stack.pop()) + Double.parseDouble(stack.pop());
stack.push(String.valueOf(result));
}
if(item.equals("-")) {
//注意减法和下面除法的出栈顺序
String a = stack.pop();
String b = stack.pop();
result = Double.parseDouble(b) - Double.parseDouble(a);
stack.push(String.valueOf(result));
}
if(item.equals("*")) {
result = Double.parseDouble(stack.pop()) * Double.parseDouble(stack.pop());
stack.push(String.valueOf(result));
}
if(item.equals("/")) {
String a = stack.pop();
String b = stack.pop();
result = Double.parseDouble(b) / Double.parseDouble(a);
stack.push(String.valueOf(result));
}
}
}
System.out.println(result);
return result;
}
public static void main(String[] args) {
new Arithmetic().caculate("(2+6)*8/3");
new Arithmetic().caculate("2+6*8/3");
new Arithmetic().caculate("6*7-3*6");
}
}