编写字符串评估功能 [英] Writing String evaluation function

查看:92
本文介绍了编写字符串评估功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写String评估函数,即

I'm trying to write a String evaluation function i.e.

evaluate("4 + 1") ; // returns 5 
evaluate("4 + 1 + 3") ; // returns 8 
evaluate("4 + 1 * 3") ; // returns 7 (not 15) 

The operators are + - / and *

尽管我最初是使用正则表达式来收集运算符和数字,因为它们可以匹配.而且,在找到该信息之后,不妨以某种方式找出优先处理/*-+运算符的方法.

My initial though was to use regular expressions to collect operators and digits as these can be matched. And than after finding that info, somehow figure out a way to prioritize /* ove -+ operators.

这是我的开始方式:

static String regex = "([\\+\\*-/])+";
static String digitRegex = "(\\d)+";

public static void main(String[] args) {
    System.out.println(getOperators("4 + 1 * 3"));
}

public static List<String> getOperators(String input) {
    Pattern p = Pattern.compile(regex);
    Matcher matcher = p.matcher(input);

    List<String> operatorList = new ArrayList<String>();

    int count = 0;
    while (matcher.find()){
        if (matcher.group(count) != null && matcher.group(count).trim().length() > 0) {
        operatorList.add(matcher.group(count));
        count++;
        }
    }

    return operatorList;
}

现在,我可以编写另一种使用相同逻辑提取数字的方法.

Now I can write another method to extract the digits using the same logic.

public static List<Integer> getDigits(String input) {
        Pattern p = Pattern.compile(digitRegex);
        Matcher matcher = p.matcher(input);

        List<Integer> digitList = new ArrayList<Integer>();

        int count = 0;
        while (matcher.find()) {
            if (matcher.group(count) != null && matcher.group(count).trim().length() > 0) {
                digitList.add(Integer.valueOf(matcher.group(count)));
                count++;
            }
        }

        return digitList;
    }

现在是我受困的部分. #1上述方法在第三个示例中失败:

Now is the part where I'm stuck. #1 This above method fails on the third example :

evaluate("4 + 1 * 3") ; // returns 7 (not 15) 

这个#2即使我尝试了前面的示例,也无法弄清楚如何以正确的顺序放置它们.

And this #2 Even if I try previous examples, I can't figure it out how to put them in the correct order.

我是完全正确的人吗,有人分享一些有用的建议吗?

Am I on the right track at all, does anyone have some useful advice please share?

推荐答案

我在这里写了一些东西...让我们说快速&肮脏是一种轻描淡写的说法...
总而言之,您不应该按原样"使用它.它需要固定"-应该使用StringTokenizer来完成数字/算术运算的读取-但我将把技术知识留给您;)

I wrote here something... let's say that quick & dirty is an understatement...
By all means, you SHOULDN'T use it "as is". It needs "fixing" - the reading of the numbers/arithmetic-operations should be done using StringTokenizer - but I'll leave the technicalities to you ;)

public class NewClass {

    public static int evaluate(String str){
        if("".equals(str)){
            return 0;
        }
        else if(str.length() == 1){
            return Integer.valueOf(str);
        }
        else{
            String _a = String.valueOf(str.charAt(0));
            String _b = String.valueOf(str.charAt(1));
            if("+".equals(_b) || "-".equals(_b) ){
                if("+".equals(_b)){
                    return Integer.valueOf(_a) + evaluate(str.substring(2));
                }
                else{// "-"
                    return Integer.valueOf(_a) - evaluate(str.substring(2));
                }
            }
            else{// "*" or "/"
                boolean isMulti = ("*".equals(_b));
                String  _c = String.valueOf(str.charAt(2));                
                Integer tmp = 0;
                if(isMulti){
                    tmp = Integer.valueOf(_a) * Integer.valueOf(_c);
                }
                else{
                    tmp = Integer.valueOf(_a) / Integer.valueOf(_c);
                }
                String new_str = String.valueOf(tmp) + str.substring(3);                
                return evaluate(new_str);
            }
        }
    }

    public static void main(String[] args){        
        String e = "4+1*3";
        int t = evaluate(e);
        System.out.println(e + " = "+t);
    }

}

这篇关于编写字符串评估功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆