在不使用API​​的情况下评估以字符串形式给出的数学表达式

时间:2013-08-22 22:17:23

标签: java string math

我想评估一个-4-12-2*12-3-4*5形式的表达式String,而不使用API​​ ,因为我是初学者,并希望掌握逻辑。

以下是我对此问题的尝试失败,如果您愿意,可以忽略并建议适当的逻辑。当然,您的代码也是受欢迎的: - )

public class SolveExpression3 {

static String testcase1 = "-4-12-2*12-3-4*5";


public static void main(String args[]){
    SolveExpression3 testInstance= new SolveExpression3();
    int result = testInstance.solve(testcase1);
    System.out.println("Result is : "+result);
}

public int solve(String str){

    int sum = 1;
    int num1 = 0;
    int num2 = 0;
    String num = "";        
    int len = str.length();
    System.out.println(str);
    for (int i = len-1 ; i >= 0; i--)
    {
        char ch = str.charAt(i);            
        if(ch == '*')
        {
            String s = "";
            num1 = num2 = 0;
            //to get the number on left of *
            for (int j = i; j >= 0; j--)
            {
                char c = str.charAt(j);                 
                if(c == '+' || c == '-' || j == 1)
                {
                    num1 = stringToInt(s);
                    s = "";
                    break;
                }
                else
                {
                    s = c + s;
                }
            }
            //to get the number on right of *
            for (int j = i; j <= len; j++)
            {
                char c = str.charAt(j);                 
                if(c == '+' || c == '-' || j == len-1)
                {
                    num2 = stringToInt(s);
                    s = "";
                    break;
                }
                else
                {
                    s = c + s;
                }
            }
            sum = sum + num1*num2;

        }
        else
        {
            num = ch + num;             
        }
    }
    len = str.length();
    for (int i = len-1; i >= 0; i--)
    {
        char ch = str.charAt(i);
        if(ch==' ')
        {}
        else if(ch=='+')
        {
            sum = sum + stringToInt(num);               
            num = "";
        }
        else if(ch=='-')
        {
            sum = sum - stringToInt(num);               
            num = "";
        }
        else
        {
            num = ch + num;             
        }
    }
    return sum;
}

public int stringToInt(String str)
{
    int number=0;
    for(int i = 0; i < str.length(); i++)
    {
        int num = str.charAt(i) - 48;
        number = number*10+num;
    }
    return number;
}

}

3 个答案:

答案 0 :(得分:1)

        found=true;
        static String testcase1 = "-4-12-2*12-3-4*5";
        Pattern SEGMENT_PATTERN = Pattern.compile("(\\d+(\\.\\d+)?|\\D+)");
        /*\\d-means digit,
        \\.-point,
        +-one or more times,
        ?-optional and 
        \\D-non digit ch*/
        Matcher matcher = SEGMENT_PATTERN.matcher(testcase1);
        while (found) {
                    boolean Found = matcher.find();
                    String segment = matcher.group();//representing a number or an operator

                        if (Character.isDigit(segment.toCharArray()[0])) {
                            //is digit
                        }
                        else {
                            //is operator

                        }
                    }

这是一个使用模式确定你是否有数字或运算符的解决方案,你只需要根据你的情况调整一下来计算结果。

You can add all the matches found to an array list than traverse it and test the operators and computer the result.

它也适用于浮动数字,例如:“它匹配5.10”。

答案 1 :(得分:0)

我会为你的目的建议一个不同的逻辑。

通常,程序算法背后的逻辑与您必须手动执行任务时应用的逻辑没有区别。

对于像你的例子那样的表达式,你通常会这样做:

  1. 找到所有*
  2. 对于每个*计算操作的结果
  3. 对+和 -
  4. 重复步骤1和2

答案 2 :(得分:0)

尝试实现一个递归下降解析器,一个描述如何实现计算器的教程(在Python中,但同样的概念适用于java)可以在这里找到http://blog.erezsh.com/how-to-write-a-calculator-in-70-python-lines-by-writing-a-recursive-descent-parser/

相关问题