java字符串计算器
时间: 2024-02-28 20:49:22 浏览: 100
以下是一个Java字符串计算器的示例代码,它可以实现基本的加减乘除和括号运算:
```java
import java.util.*;
public class StringCalculator {
private static final Map<String, Integer> priorityMap = new HashMap<String, Integer>() {{
put("+", 1);
put("-", 1);
put("*", 2);
put("/", 2);
put("%", 2);
put("^", 3);
}};
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入表达式:");
String expression = scanner.nextLine();
System.out.println("计算结果为:" + calculate(expression));
}
public static String calculate(String s) {
List<String> arrayList = reversePolish.parse(s);
Stack<String> stringStack = new Stack<>();
for (int i = 0; i < arrayList.size(); i++) {
String str = arrayList.get(i);
if (str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/") || str.equals("^") || str.equals("%")) {
cal(stringStack, str);
} else {
stringStack.push(str);
}
}
return stringStack.pop();
}
private static void cal(Stack<String> stack, String op) {
String b = stack.pop();
String a = stack.pop();
String result = "";
switch (op) {
case "+":
result = String.valueOf(Double.parseDouble(a) + Double.parseDouble(b));
break;
case "-":
result = String.valueOf(Double.parseDouble(a) - Double.parseDouble(b));
break;
case "*":
result = String.valueOf(Double.parseDouble(a) * Double.parseDouble(b));
break;
case "/":
result = String.valueOf(Double.parseDouble(a) / Double.parseDouble(b));
break;
case "^":
result = String.valueOf(Math.pow(Double.parseDouble(a), Double.parseDouble(b)));
break;
case "%":
result = String.valueOf(Double.parseDouble(a) % Double.parseDouble(b));
break;
}
stack.push(result);
}
private static class reversePolish {
public static List<String> parse(String s) {
List<String> arrayList = new ArrayList<>();
Stack<String> stack = new Stack<>();
int i = 0;
while (i < s.length()) {
char c = s.charAt(i);
if (Character.isDigit(c) || c == '.') {
int j = i;
while (j < s.length() && (Character.isDigit(s.charAt(j)) || s.charAt(j) == '.')) {
j++;
}
arrayList.add(s.substring(i, j));
i = j;
} else if (c == '(') {
stack.push("(");
i++;
} else if (c == ')') {
while (!stack.peek().equals("(")) {
arrayList.add(stack.pop());
}
stack.pop();
i++;
} else {
String op = String.valueOf(c);
while (!stack.isEmpty() && !stack.peek().equals("(") && priorityMap.get(op) <= priorityMap.get(stack.peek())) {
arrayList.add(stack.pop());
}
stack.push(op);
i++;
}
}
while (!stack.isEmpty()) {
arrayList.add(stack.pop());
}
return arrayList;
}
}
}
```
阅读全文