import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class PolandNotation {
public static List<String> parseSuffixExpression(List<String> list) {
List<String> res = new ArrayList<>(16);
Stack<String> operator = new Stack<>();
String lbrace = "(";
String rbrace = ")";
for (String str : list) {
if (CommonUtil.isDigital(str)) {
res.add(str);
} else if (lbrace.equals(str)) {
operator.push(str);
} else if (rbrace.equals(str)) {
while (!operator.empty() && !lbrace.equals(operator.peek())) {
res.add(operator.pop());
}
if (!operator.empty()) {
operator.pop();
}
} else {
while (!operator.empty() && getPriorityOfOperator(operator.peek()) >= getPriorityOfOperator(str)) {
res.add(operator.pop());
}
operator.push(str);
}
}
while (!operator.empty()) {
res.add(operator.pop());
}
return res;
}
public static int getPriorityOfOperator(String operator) {
int priority = 0;
switch (operator) {
case "+":
case "-": {
priority = 1;
break;
}
case "*":
case "/": {
priority = 2;
break;
}
default:
break;
}
return priority;
}
}
import java.util.List;
public class DemoTest {
public static void main(String[] args) {
String str = "8 + ((2 + 5) * 6) + 10.5";
List<String> list = CommonUtil.parseArithmeticStr(str);
List<String> suffixExpression = PolandNotation.parseSuffixExpression(list);
System.out.println(suffixExpression);
}
}
import java.util.List;
import java.util.Stack;
public class DemoTest {
public static void main(String[] args) {
String str = "8 + ((2 + 5) * 6) + 10.5";
System.out.println(str.replaceAll(" +", ""));
List<String> list = CommonUtil.parseArithmeticStr(str);
List<String> suffixExpression = PolandNotation.parseSuffixExpression(list);
System.out.println(suffixExpression);
calculate(suffixExpression);
}
public static void calculate(List<String> list) {
Stack<String> stack = new Stack<>();
for (String str : list) {
if (CommonUtil.isDigital(str)) {
stack.push(str);
} else {
Double d2 = Double.parseDouble(stack.pop());
Double d1 = Double.parseDouble(stack.pop());
stack.push(operate(d1, str, d2));
}
}
System.out.println("计算结果: " + Double.parseDouble(stack.pop()));
}
public static String operate(Double d1, String ope ,Double d2) {
String str = "";
switch (ope) {
case "+": {
str = (d1 + d2) + "";
break;
}
case "-": {
str = (d1 - d2) + "";
break;
}
case "*": {
str = (d1 * d2) + "";
break;
}
case "/": {
str = (d1 / d2) + "";
break;
}
default:
break;
}
return str;
}
}