0

这是我编写的用于检查哪个运算符具有最高优先级的方法,现在我的问题是:还有其他方法可以做到这一点吗?我一直在测试这个,它工作正常,但我很确定应该有改进的空间。你怎么看?

static boolean hasHigherPrecendence(char top, char current){

    String t = String.valueOf(top);
    String c = String.valueOf(current);

    System.out.println(t);
    System.out.println(c);

    switch (t) {
    case "-":
        if ( c.equals("-") || c.equals("+") )
            return false;
        break;      
    case "+":
        if ( c.equals("-") || c.equals("+") )
            return false;
        break;          
    case "/":
        if ( !c.equals("*") || !c.equals(t) || !c.equals("%") )
            return false;
        break;      
    case "*":
        if ( !c.equals("%") || !c.equals(t) || !c.equals("/"))
            return false;
        break;
    case "%":
        if (c.equals(t) || c.equals("*") || c.equals("/"))
            return false;
        break;          
    default:
        throw new IllegalArgumentException("Operator unknown: " + t);
    }       

    return true;
}
4

3 回答 3

4

如果是我,我会对函数中的运算符进行排名(注意,我选择的值不一定是你应该使用的值......):

private static final int rankOperator(char op) {
    switch (op) {
        case '-' : return 0;
        case '+' : return 0;
        case '/' : return 2;
        case '*' : return 2;
        case '%' : return 4;
    }
    throw new IllegalStateException("Unknown operator " + op);
}


public boolean hasHigherPrecedence(char top, char current) {
    return rankOperator(top) > rankOperator(current);
}
于 2013-11-07T16:03:28.810 回答
1

除了使用地图、数组、函数......您可以使用连接具有相同行为的案例来减少代码:

static boolean hasHigherPrecendence(char top, char current){

    String t = String.valueOf(top);
    String c = String.valueOf(current);

    System.out.println(t);
    System.out.println(c);

    switch (t) {
    case "-":
    case "+": 
        if ( c.equals("-") || c.equals("+") )
            return false;
        break;              
    case "/": 
    case "*":
    case "%":
        if (c.equals("%") || c.equals("*") || c.equals("/"))
            return false;
        break;          
    default:
        throw new IllegalArgumentException("Operator unknown: " + t);
    }       

    return true;
}
于 2013-11-07T16:41:22.710 回答
1
static boolean hasHigherPrecendence(char top, char current){
    Map<Character,Integer> map = new HashMap<>();
    map.put('+',new Integer(1));
    map.put('-',new Integer(1));
    map.put('*',new Integer(2));
    map.put('/',new Integer(2));
    map.put('%',new Integer(3));
    if( map.get(top)==null ){
        throw new IllegalArgumentException("Operator unknown: " + top);
    }
    if( map.get(current)==null ){
        throw new IllegalArgumentException("Operator unknown: " + current);
    }
    if(map.get(t) >= map.get(c)){
        return true;
    }else{
        return false;
    }
}
于 2013-11-07T16:29:58.920 回答