import java.util.HashMap;
import java.util.Vector;
public class Calculator {
private Vector<Double> expressionValue = new Vector<>(); // 值
private Vector<String> expressionOperator = new Vector<>(); // 运算符
// 执行 + - * / 计算
private synchronized void calculate() {
String b = expressionOperator.remove(expressionOperator.size() - 1);
double c = expressionValue.remove(expressionValue.size() - 1);
double d = expressionValue.remove(expressionValue.size() - 1);
double e;
if (b.equals("+")) {
e = d + c;
expressionValue.add(e);
} else if (b.equals("-")) {
e = d - c;
expressionValue.add(e);
} else if (b.equals("*")) {
e = d * c;
expressionValue.add(e);
} else if (b.equals("/")) {
if (c == 0)
throw new ArithmeticException("除 0 错误!");
e = d / c;
expressionValue.add(e);
}
}
// 计算字符串的值
public synchronized Double calculate(String text) {
HashMap<String, Integer> operator = new HashMap<>();
operator.put("(", 0);
operator.put(")", 0);
operator.put("/", 2);
operator.put("*", 2);
operator.put("-", 1);
operator.put("+", 1);
operator.put("#", 0);
expressionOperator.add("#");
int flag = 0;
int n = text.length();
for (int i = 0; i < n; i++) {
String a = String.valueOf(text.charAt(i));
if (!a.matches("[0-9.]")) {
if (flag != i) {
expressionValue.add(Double.parseDouble(text.substring(flag, i)));
}
flag = i + 1;
while (!(a.equals("#") && expressionOperator.lastElement().equals("#"))) { // lastElement 返回栈顶元素,不删除
if (operator.get(a) > operator.get(expressionOperator.lastElement()) || a.equals("(")) {
expressionOperator.add(a); // 加入操作符
break;
} else {
if (a.equals(")")) {
while (!expressionOperator.lastElement().equals("("))
calculate();
expressionOperator.remove(expressionOperator.size() - 1);
break;
}
calculate();
}
}
}
}
return expressionValue.remove(expressionValue.size() - 1);
}
public static void main(String[] args) {
// 单线程测试
Double calculate = new Calculator().calculate("1/2*(2-2)" + "#");
System.out.println(calculate);
// 多线程测试
testMultithreading();
}
public static void testMultithreading() {
String[] expressions = {
"1+2*3",
"4/2-1",
"(1+2)*3",
"10-5/2",
"10-5/2",
"10-5/2",
"10-5/2",
"10-5/2",
"10-5/2",
"10-5/2",
"10-5/2",
"10-5/2",
"10-5/2",
"10-5/2",
"10-5/2"
};
Thread[] threads = new Thread[expressions.length];
for (int i = 0; i < expressions.length; i++) {
final int index = i;
threads[i] = new Thread(() -> {
Calculator calculator = new Calculator();
double result = calculator.calculate(expressions[index] + "#");
System.out.println("Expression: " + expressions[index] + " = " + result);
});
threads[i].start();
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
根据字符串加减乘除输出结果工具类
最新推荐文章于 2025-04-11 00:16:46 发布