簡體   English   中英

在 Java 中替換嵌套 While 循環的替代方法

[英]Alternative way to replace Nested While Loop in Java

我嘗試使用以下代碼評估 Java 中的數學表達式:

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();
}

輸入示例:

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

上面的代碼工作正常,但我想知道有什么方法可以替換

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

用其他東西,所以我不必在這種情況下使用嵌套的 while 循環。 目標是在字符串中捕獲數字,直到它到達運算符
提前致謝

您可以像這樣使用正則表達式。

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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM