HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Parsing expression with exponents and evaluating

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
expressionexponentswithparsingandevaluating

Problem

I'm programming a basic command line calculator in java that can parse expressions and evaluate them, does not handle brackets yet.

For example an expression: \$9+9/2^2*5-1\$.

At this point I can give my program an expression that contains exponents, and It will evaluate them one by one until there are none left.

For example, I can input the following string: \$2^2+1\$ and it will output \$4.0+1\$.

```
public class Main {

public static void main(String[] args) {
String powerExpression = "2^2+1";

loopPower(powerExpression);
}

public static void loopPower(String exp) {
while (containsExponents(exp)) {
exp = procPower(exp);
}

System.out.println("FINAL ANSWER IS: " + exp);

}
public static boolean containsExponents(String exp) {
boolean contains = false;
for (int i = 0; i 0 & operandTwoEnd 0 & operandTwoEnd == (exp.length()-1)) {
yesBeforenoAfter = true;
String before = "";
for (int a = 0;a < operandOneStart;a++) {
before += exp.charAt(a);
}
double subans = Math.pow(opx1,opx2);
exp = before+subans;
}

//
break;
}
}
else {
if (exp.charAt(i) == '^') {
foundOp = true;
}
else {
onFirst = true;
foundOp = false;
}
}
}

return exp;
}

public static boolean isCharNumerical(char c) {
boolean numerical = false;

switch (c) {
case '0':
numerical = true;
break;
case '1':
numerical = true;
break;
case '2':
numerical = true;

Solution

Just for one thing: The isCharNumerical() function doesn't actually need a switch statement, it could be simplified just as

public static boolean isCharNumerical(char c) {   
    return (c >= '0' && c <= '9');
}


Don't overcomplicate boolean conditions, just take them straightforward.

In general for your parser, make operator precedence clear at any state of parsing.

What you have in your example clearly states that operator ^ precedes operator +, which is the natural expectation. Require brackets to group math expressions being processed in different order.

Code Snippets

public static boolean isCharNumerical(char c) {   
    return (c >= '0' && c <= '9');
}

Context

StackExchange Code Review Q#114589, answer score: 5

Revisions (0)

No revisions yet.