本文介绍了JAVA中BODMAS的算法计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经为Bodmas编写了这段代码,但是在这里遇到了一些错误。如果我做3-5 + 9,它将导致-3.04.0
它只是开始连接,虽然它适用于所有其他操作,如*,/和 -
请帮忙。

I have written this code for Bodmas, but getting some error in this. If i do 3-5+9, it will result to- 3.04.0It just start concatenating, though it works for all other operations like *, / and -Please help.

public static String calculation(BODMASCalculation bodmas, String result) {
    while (bodmas.hasMatch()) {
        double value, leftOfOperator = bodmas.getLeft();
        char op = bodmas.getOperator();
        double rightOfOprator = bodmas.getRight();

        switch (op) {
        case '/':
            if(rightOfOprator == 0) //Divide by 0 generates Infinity
                value = 0;
            else
                value = leftOfOperator / rightOfOprator;
            break;
        case '*':
            value = leftOfOperator * rightOfOprator;
            break;
        case '+':
            value = leftOfOperator + rightOfOprator;
            break;
        case '-':
            value = leftOfOperator - rightOfOprator;
            break;
        default:
            throw new IllegalArgumentException("Unknown operator.");
        }           
        result = result.substring(0, bodmas.getStart()) + value + result.substring(bodmas.getEnd());
        bodmas = new BODMASCalculation(result);
    }
    return result;
}

另一项功能是: -

Another function is:-

public boolean getMatchFor(String text, char operator) {
    String regex = "(-?[\\d\\.]+)(\\x)(-?[\\d\\.]+)";
    java.util.regex.Matcher matcher = java.util.regex.Pattern.compile(regex.replace('x', operator)).matcher(text);
    if (matcher.find()) {
        this.leftOfOperator = Double.parseDouble(matcher.group(1));
        this.op = matcher.group(2).charAt(0);
        this.rightOfOprator = Double.parseDouble(matcher.group(3));
        this.start = matcher.start();
        this.end = matcher.end();
        return true;
    }
    return false;
}

我有一个addind的解决方案 -

I have a Solution by addind -

String sss = null;
        if(op == '+' && !Str.isBlank(result.substring(0, bodmas.getStart())) && value >= 0)
            sss = "+";
        else
            sss = "";
        result = result.substring(0, bodmas.getStart()) + sss + value   + result.substring(bodmas.getEnd());

但是不想这样做,我希望这适用于所有运营商。
感谢提前。

But don't want to do that, I want this to work for all the operators.THANKS IN ADVANCE.

推荐答案

import java.util.Stack;

public class EvaluateString
{
    public static int evaluate(String expression)
    {
        char[] tokens = expression.toCharArray();

         // 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 whitespace, skip it
            if (tokens[i] == ' ')
                continue;

            // 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 opening brace, push it to 'ops'
            else if (tokens[i] == '(')
                ops.push(tokens[i]);

            // Closing brace encountered, solve entire brace
            else if (tokens[i] == ')')
            {
                while (ops.peek() != '(')
                  values.push(applyOp(ops.pop(), values.pop(), values.pop()));
                ops.pop();
            }

            // 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 (op2 == '(' || op2 == ')')
            return false;
        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("10 + 2 * 6"));
        System.out.println(EvaluateString.evaluate("100 * 2 + 12"));
        System.out.println(EvaluateString.evaluate("100 * ( 2 + 12 )"));
        System.out.println(EvaluateString.evaluate("100 * ( 2 + 12 ) / 14"));
    }
}

这篇关于JAVA中BODMAS的算法计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 21:56