代码拉取完成,页面将自动刷新
import java.util.Stack;
import java.util.regex.Pattern;
public class StringToArithmetic {
public StringToArithmetic() {
}
public static String stringToArithmetic(String string) {return suffixToArithmetic(infixToSuffix(string));}
public static String infixToSuffix(String exp) {
Stack<Character> s = new Stack<Character>();
String suffix = "";
int length = exp.length();
for (int i = 0; i < length; i++) {
char temp;
char ch = exp.charAt(i);
switch (ch) {
case ' ':
break;
case '(':
s.push(ch);
break;
case '+':
case '-':
while (s.size() != 0) {
temp = s.pop();
if (temp == '(') {
s.push('(');
break;
}
suffix += temp;
}
s.push(ch);
break;
case '*':
case '/':
while (s.size() != 0) {
temp = s.pop();
if (temp == '+' || temp == '-' || temp == '(') {
s.push(temp);
break;
} else {
suffix += temp;
}
}
s.push(ch);
break;
case ')':
while (!s.isEmpty()) {
temp = s.pop();
if (temp == '(') {
break;
} else {
suffix += temp;
}
}
break;
default:
suffix += ch;
break;
}
}
while (s.size() != 0) {
suffix += s.pop();
}
return suffix;
}
public static String suffixToArithmetic(String exp) {
Pattern pattern = Pattern.compile("\\d+||(\\d+\\.\\d+)");
String[] strings = exp.split("");
Stack<Double> stack = new Stack<Double>();
for (int i = 0; i < strings.length; i++) {
if (strings[i].equals("")) {
continue;
}
if (pattern.matcher(strings[i]).matches()) {
stack.push(Double.parseDouble(strings[i]));
}
else {
double y = stack.pop();
double x = stack.pop();
stack.push(calculate(x, y, strings[i]));
}
}
return String.valueOf(stack.pop());
}
private static Double calculate(double x, double y, String string) {
if (string.trim().equals("+")) {
return x + y;
}
if (string.trim().equals("-")) {
return x - y;
}
if (string.trim().equals("*")) {
return x * y;
}
if (string.trim().equals("/")) {
return x / y;
}
return (double) 0;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。