有些基础知识有欠缺,补一下,顺便练习一下java
import com.sun.deploy.util.ArrayUtil;
import java.util.*;
public class Main {
public static int op_priority(char c) {
switch (c) {
case '(':
return 18;
case '+':
case '-':
return 1;
case '*':
case '/':
return 4;
default:
return -1;
}
}
private static Set<Character> operators = new HashSet<>();
static
{
operators.add('+');
operators.add('-');
operators.add('*');
operators.add('/');
operators.add('(');
operators.add(')');
}
public static String infix2postfix(String exp) throws Exception {
Stack<Character> ops = new Stack<Character>();
StringBuilder sb = new StringBuilder();
List<String> result = new ArrayList<>();
int i = 0;
String digit = new String();
while (i < exp.length()) {
char c = exp.charAt(i);
if (!operators.contains(c)) {
digit += c;
} else {
if (!digit.isEmpty())
result.add(digit);
digit = "";
if (ops.empty()) {
ops.push(c);
} else if (c == ')') {
while (!ops.empty() && ops.peek() != '(') {
result.add(ops.pop().toString());
}
if (ops.empty()) {
throw new Exception("no (");
} else {
ops.pop(); // pop (
}
} else if (op_priority(ops.peek()) < op_priority(c)) {
ops.push(c);
} else if (ops.peek() == '(') {
ops.push(c);
} else {
result.add(ops.pop().toString());
ops.push(c);
digit += exp.charAt(i + 1);
++i;
}
}
++i;
}
if (digit != "") {
result.add(digit);
}
while (ops.size() > 0) {
result.add(ops.pop().toString());
}
for (String s : result) {
sb.append(s);
sb.append(" ");
}
return sb.toString();
}
public static double calc_temp(Character op, double v1, double v2) {
switch (op) {
case '+':
return v1 + v2;
case '-':
return v1 - v2;
case '*':
return v1 * v2;
case '/':
return v1 / v2;
}
return 0;
}
public static double calc(String postfix) throws Exception{
Stack<Double> vstack = new Stack<>();
for (String v : postfix.split(" ")) {
if (v.length() == 1 && !Character.isDigit(v.charAt(0))) {
if (vstack.size() >= 2) {
double temp = calc_temp(v.charAt(0), vstack.pop(), vstack.pop());
vstack.push(temp);
}
else {
throw new Exception("error");
}
} else {
System.out.println(v);
vstack.push(Double.parseDouble(v));
}
}
return vstack.pop();
}
public static void main(String[] args) {
try {
String exp = infix2postfix("(2+3)*4+1.3*(2+1)");
System.out.println(exp);
System.out.println(calc(exp.trim()));
} catch (Exception ex) {
System.out.println(ex.getMessage());
System.out.println(ex.getCause());
ex.printStackTrace();
}
System.out.println();
System.out.println("Hello World!");
}
}