Skip to content

Commit a1c1ab0

Browse files
author
Eble
committed
PlusMinusExpr
1 parent faa0a38 commit a1c1ab0

3 files changed

Lines changed: 17 additions & 3 deletions

File tree

src/main/java/com/ExpressionEvaluatorMain.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ public class ExpressionEvaluatorMain {
55
public static void main(String[] args) throws Exception {
66
com.compiler.Lexer lexer = new com.compiler.Lexer();
77
com.compiler.ExpressionEvaluator evaluator = new com.compiler.ExpressionEvaluator(lexer);
8-
int result = evaluator.eval("4+5");
8+
int result = evaluator.eval("4-5-3+2");
99
System.out.println(result);
1010
}
1111

src/main/java/com/compiler/ExpressionEvaluator.java

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,23 @@ int getUnaryExpr() throws Exception {
3030
int getMulDivExpr() throws Exception {
3131
return getUnaryExpr();
3232
}
33-
33+
3434
int getPlusMinusExpr() throws Exception {
35+
// sumExpr: mulExpr (sumOp mulExpr)*
3536
int result = getMulDivExpr();
37+
while (
38+
m_lexer.lookAhead().m_type == TokenIntf.Type.PLUS ||
39+
m_lexer.lookAhead().m_type == TokenIntf.Type.MINUS
40+
) {
41+
TokenIntf.Type tokenType = m_lexer.lookAhead().m_type;
42+
m_lexer.advance(); // getSumOp()
43+
int op = getMulDivExpr();
44+
if (tokenType == TokenIntf.Type.PLUS) {
45+
result += op;
46+
} else {
47+
result -= op;
48+
}
49+
}
3650
return result;
3751
}
3852

src/test/java/com/compiler/TestPlusMinusExpr.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ public class TestPlusMinusExpr extends TestExpressionEvaluatorBase {
88

99
@Test
1010
public void testPlusMinusExpr() throws Exception {
11-
assertEquals(5, evalExpression("5"));
11+
assertEquals(5+42-19, evalExpression("5+42-19"));
1212
}
1313

1414
}

0 commit comments

Comments
 (0)