Krolyxon
Commit d134acd

Branches

Refs →

jcald134acd

fix duplicate digit at end

Author
krolxon
Date
2024-02-15 00:09 +0530
Parent
4cea67a
Commit
d134acdbc12a2d16dadc129f233daeec2b1c9fb8

+22 −5

4 files changed

  1. M Calculator.java +7 −1
  2. M Parser.java +15 −4
  3. A bin/Calculator.class
  4. A bin/Parser.class
M Calculator.java View
@@ -1,8 +1,14 @@
11 public class Calculator {
22 public static void main(String[] args) {
33 String expr = "(84 / 4 * 3 - 9) * 2 + 1 / 5"; // 108.2
4− Parser p = new Parser(expr);
4+ Parser p;
5+ if (args.length == 0) {
6+ p = new Parser(expr);
7+ } else {
8+ p = new Parser(args[0]);
9+ }
510 String postfix = p.toPostFix();
11+ // System.out.println("pfix => \t " + postfix);
612 System.out.println(p.evalExpr(postfix));
713 }
814 }
M Parser.java View
@@ -1,4 +1,6 @@
11 /* Todo
2+* - Fix this:
3+* when expression = 5+10*(10), it misses +
24 * - Add support for trigonometric functions
35 * - Remove all edge cases
46 */
@@ -70,6 +72,9 @@ public class Parser {
7072 // Main Expression Iteration
7173 for (int i = 0; i < infix.length; i++) {
7274 char c = infix[i];
75+
76+ // Keep appending digits to the operand StringBuilder and skip iterations till
77+ // we find a operator.
7378 if (isOperand(c)) {
7479 operand.append(infix[i]);
7580 if (i < infix.length - 1) {
@@ -90,14 +95,22 @@ public class Parser {
9095 }
9196 operatorStack.pop();
9297 } else {
98+ // Manage precedence order of operatorStack operators
9399 while (!operatorStack.isEmpty() && getPresedence(c) <= getPresedence((char) operatorStack.peek())
94100 && hasLeftAssociativity(c)) {
95101 output.add(operatorStack.pop().toString());
96102 }
97− operatorStack.push(c);
103+
104+ // For whatever reason, the last digit gets added to the operatorStack, leading
105+ // to a duplicate of last digit in the expression
106+ // To fix this, we again make sure that the current char is not a operand.
107+ if (!isOperand(c)) {
108+ operatorStack.push(c);
109+ }
98110 }
99111 }
100112
113+ // pop all the operators left in the operatorStack after the loop is done.
101114 while (!operatorStack.isEmpty()) {
102115 if (operatorStack.peek() == '(') {
103116 return "This expression is invalid";
@@ -105,9 +118,7 @@ public class Parser {
105118 output.add(operatorStack.pop().toString());
106119 }
107120
108− // last digit gets duplicate entry for some reason, so have to remove it.
109− String op = output.toString();
110− return op.substring(0, op.length() -2);
121+ return output.toString();
111122 }
112123
113124 private Double evaluate(String operator, Double op1, Double op2) {
A bin/Calculator.class View

[Binary file]

A bin/Parser.class View

[Binary file]