Hoàng Việt
Hoàng Việt

Reputation: 174

Alternative way to replace Nested While Loop in Java

I tried to Evaluate Mathematical Expressions in Java with the following code:

public double applyOp(char op,double b,double a)
{
    switch (op)
    {
        case '+':
            return a + b;
        case '-':
            return a - b;
        case '*':
            return a * b;
        case '/':
            return a / b;
    }
    return 0;
}

public boolean hasPrecedence(char op1,char op2)
{
    return (op1 != '*' && op1 != '/') || (op2 != '+' && op2 != '-');
}

public double evaluate(String input) {
    Stack<Double> values = new Stack<>();
    Stack<Character> ops = new Stack<>();
    int stringIndex = 0;

    while (stringIndex < input.length())
    {
        StringBuilder multiDigitsNumber = new StringBuilder();

        // If the input is number put to stack values
        if (input.charAt(stringIndex) >= '0' && input.charAt(stringIndex) <= '9')
        {
            while (stringIndex < input.length() && input.charAt(stringIndex) >= '0' && input.charAt(stringIndex) <= '9')
            {
                multiDigitsNumber.append(input.charAt(stringIndex++));
            }
            values.push(Double.parseDouble(multiDigitsNumber.toString()));
        }

        // If the input is operator put to stack ops
        else
        {
            while (!ops.empty() && hasPrecedence(input.charAt(stringIndex),ops.peek()))
            {
                values.push(applyOp(ops.pop(),values.pop(),values.pop()));
            }
            ops.push(input.charAt(stringIndex++));
        }
    }

    // Execute remain operator in stack values
    while (!ops.empty()) {
        values.push(applyOp(ops.pop(), values.pop(), values.pop()));
    }

    // The final number in stack value is result
    return values.pop();
}

Input example:

12+24*2-30/5.....

The code above works fine but I wonder are there any way to replace

while (stringIndex < input.length() && input.charAt(stringIndex) >= '0' && input.charAt(stringIndex) <= '9')
        {
            multiDigitsNumber.append(input.charAt(stringIndex++));
        }

with something else so I don't have to use nested while loop in this situation. The goal is to catch number in string until it reach an operator
Thanks in advance

Upvotes: 0

Views: 314

Answers (1)

user4910279
user4910279

Reputation:

You can use Regex like this.

if (input.charAt(stringIndex) >= '0' && input.charAt(stringIndex) <= '9')
{
    String number = input.substring(stringIndex).replaceAll("^(\\d+).*", "$1");
    values.push(Double.parseDouble(number));
    stringIndex += number.length();
}

Upvotes: 1

Related Questions