0

My code fails when I input something like 3(5). How do I modify my code so that it solves in expression in the middle and then multiplies?

double parseTerm() {
    double x = parseFactor();
    while(true) {
        if      (shift('*')){
            x *= parseFactor(); // multiply
        }
        else if (shift('/')){
            x /= parseFactor(); // divide
        }
        else{
            return x;
        }
    }
}

double parseExpression() {
    double x = parseTerm();
    while(true) {
        if      (shift('+')){
            x += parseTerm(); // addition
        }
        else if (shift('-')){
            x -= parseTerm(); // subtraction
        }
        else{
            return x;
        }
    }
}

double parseFactor() {
    if (shift('+')){
        return parseFactor(); //plus
    }
    if (shift('-')){
        return -parseFactor(); //minus
    }

    double x;
    int startPos = this.pos;

    if (shift('(')) { // brackets
        x = parseExpression();
        shift(')');
user207421
  • 305,947
  • 44
  • 307
  • 483
byzht
  • 11
  • 2
  • 5
    Why is this tagged with both Java and JavaScript? – Logan Jun 03 '17 at 01:40
  • 2
    For all those who wonder: [BEDMAS, standing for Brackets, Exponents, Division, Multiplication, Addition, Subtraction](https://en.wikipedia.org/wiki/Order_of_operations) = order of operations – le_m Jun 03 '17 at 01:41
  • 1
    Please post a [mcve] - one that is both *minimal* and **complete** - the code above is not complete and I don't think it's minimal either. Then give make your own attempt - and if it doesn't work, show what you tried and what goes wrong in detail. As a hint - if you want an opening parenthesis `(` act as a de-facto multiplication operator, then you need to put something like what you have in the `parseFactor` method for sub expression in the `parseTerm` method as well. – Erwin Bolwidt Jun 03 '17 at 02:01
  • `3(5)` is not a legal input according to your code. Do you mean `3*(5)`? – user207421 Jun 03 '17 at 02:24

1 Answers1

0

This is what you'd need to change in parseTerm to get an expression like 3(5) working the same as 3*(5):

double parseTerm() {
    double x = parseFactor();
    while(true) {
        if (shift('*')) {
            x *= parseFactor(); // multiply
        } else if (shift('/')) {
            x /= parseFactor(); // divide
        } else if (shift('(')) { // brackets
            x *= parseExpression();
            shift(')');
        } else {
            return x;
        }
    }
}

(This is assuming that your parseFactor method is correct, because it's incomplete in your code)

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79