File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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
Original file line number Diff line number Diff 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
Original file line number Diff line number Diff 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}
You can’t perform that action at this time.
0 commit comments