有以下代码:
public static double evaluate(final String str){
class Parser {
int pos = -1;
int c;
void eatChar() {
c = (++pos < str.length()) ? str.charAt(pos) : -1;
}
void eatSpace() {
while (Character.isWhitespace(c)) eatChar();
}
//Everything below this point confuses me xD
double parse() {
eatChar();
double v = parseExpression();
if (c != -1) throw new RuntimeException("Unexpected: " + (char)c);
return v;
}
double parseExpression() {
double v = parseTerm();
for (;;) {
eatSpace();
if (c == '+') { // addition
eatChar();
v += parseTerm();
} else if (c == '-') { // subtraction
eatChar();
v -= parseTerm();
} else {
return v;
}
}
}
double parseTerm() {
double v = parseFactor();
for (;;) {
eatSpace();
if (c == '/' || c == '÷') { // division
eatChar();
v /= parseFactor();
} else if (c == '*' || c == '(') { // multiplication
if (c == '*') eatChar();
v *= parseFactor();
} else {
return v;
}
}
}
double parseFactor() {
double v;
boolean negate = false;
eatSpace();
if (c == '+' || c == '-') { // unary plus & minus
negate = c == '-';
eatChar();
eatSpace();
}
if (c == '(') { // brackets
eatChar();
v = parseExpression();
if (c == ')') eatChar();
} else { // numbers
int startIndex = this.pos;
while ((c >= '0' && c <= '9') || c == '.') eatChar();
if (pos == startIndex) throw new RuntimeException("Unexpected: " + (char)c);
v = Double.parseDouble(str.substring(startIndex, pos));
}
eatSpace();
if (c == '^') { // exponentiation
eatChar();
v = Math.pow(v, parseFactor());
}
if (negate) v = -v;
return v;
}
}
return new Parser().parse();
}
发布于 2018-07-25 13:56:30
这样试试:
Get the first factor
while there's operators (+,-,/,% etc) after that factor,
then get the next factor and perform that operation with the two factors
https://stackoverflow.com/questions/-100005729
复制相似问题