java - 中缀算法仅返回最后一个数字

标签 java math infix-notation

我有以下类来评估公式并返回结果。它使用中缀算法和2个不同的堆栈来推送值和运算符。当公式有空格分隔字符时,例如:2 + 3 * 4,它可以工作,但当它没有空格时,例如:2+3*4 它不起作用。我需要该功能在没有空格的情况下工作,但我看不到必须修改代码的位置。

package calculator;

import java.util.Stack; 

public class EvaluateString 
{ 
    public static int evaluate(String expression) 
    { 
            System.out.println(expression);
        char[] tokens = expression.toCharArray(); 
                System.out.println(tokens);
        // Stack for numbers: 'values' 
        Stack<Integer> values = new Stack<Integer>(); 

        // Stack for Operators: 'ops' 
        Stack<Character> ops = new Stack<Character>(); 

        for (int i = 0; i < tokens.length; i++) 
        { 

            // Current token is a number, push it to stack for numbers 
            if (tokens[i] >= '0' && tokens[i] <= '9') 
            { 
                StringBuffer sbuf = new StringBuffer(); 
                // There may be more than one digits in number 
                while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9') 
                    sbuf.append(tokens[i++]); 
                values.push(Integer.parseInt(sbuf.toString())); 
            } 


            // Current token is an operator. 
            else if (tokens[i] == '+' || tokens[i] == '-' || 
                    tokens[i] == '*' || tokens[i] == '/') 
            { 
                // While top of 'ops' has same or greater precedence to current 
                // token, which is an operator. Apply operator on top of 'ops' 
                // to top two elements in values stack 
                while (!ops.empty() && hasPrecedence(tokens[i], ops.peek())) 
                values.push(applyOp(ops.pop(), values.pop(), values.pop())); 

                // Push current token to 'ops'. 
                ops.push(tokens[i]); 
            } 
        } 

        // Entire expression has been parsed at this point, apply remaining 
        // ops to remaining values 
        while (!ops.empty()) 
            values.push(applyOp(ops.pop(), values.pop(), values.pop())); 

        // Top of 'values' contains result, return it 
        return values.pop(); 
    } 

    // Returns true if 'op2' has higher or same precedence as 'op1', 
    // otherwise returns false. 
    public static boolean hasPrecedence(char op1, char op2) 
    { 

        if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) 
            return false; 
        else
            return true; 
    } 

    // A utility method to apply an operator 'op' on operands 'a' 
    // and 'b'. Return the result. 
    public static int applyOp(char op, int b, int a) 
    { 
        switch (op) 
        { 
        case '+': 
            return a + b; 
        case '-': 
            return a - b; 
        case '*': 
            return a * b; 
        case '/': 
            if (b == 0) 
                throw new
                UnsupportedOperationException("Cannot divide by zero"); 
            return a / b; 
        } 
        return 0; 
    } 

    // Driver method to test above methods 
    public static void main(String[] args) 
    { 
        System.out.println(EvaluateString.evaluate("100*2+12")); 
    } 
}

最佳答案

用于推送操作的第二个 if 语句永远不会被执行,因为您实际上通过内部 while 循环跳过了该操作 [i++]

 while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9') 
                sbuf.append(tokens[i++]); 

但是当您用空格分隔字符时,例如:2 + 3 * 4它之所以有效,是因为您尚未通过 [i++] 跳过该操作

您可以简单地decrease the counter指定要推送到您的 values 的号码后堆栈

if (tokens[i] >= '0' && tokens[i] <= '9') 
        { 
            StringBuffer sbuf = new StringBuffer(); 
            // There may be more than one digits in number 
            while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9') 
                sbuf.append(tokens[i++]); 
            values.push(Integer.parseInt(sbuf.toString())); 
            --i;
        } 

关于java - 中缀算法仅返回最后一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54302425/

相关文章:

Java小程序白屏

查找与 Ax+By+C=0 形式的给定直线垂直的直线的算法

math - float 学坏了吗?

java - 将字符串转换为字符串数组

java - 从数组创建二维矩阵 (java)

java - 插入时oracle + java编码问题

math - 如何减轻排名系统中的跟风效应(投票行为)?

java - Postfix 评估器未返回正确的结果

java - 尝试将中缀转换为后缀返回向后输出

java - 必需的: variable Found:value Error Java Text-Based Calculator