算术表达式的解析器

时间:2013-11-19 02:05:37

标签: java parsing math arithmetic-expressions

我正在尝试实现一个简单的解析器来解决算术表达式,例如  “(9 + 7)*(10-4)”。现在我只是通过一些简单的计算测试我的代码,如“9 + 7”等。它允许用户输入一个字符串,但在我输入表达式后点击输入,没有任何反应(控制台中的空白)。这是我的代码:

public class parser {
//check whether if a string is an integer 
public static boolean isInteger (String s){
    try{
        Integer.parseInt(s);
    }catch(NumberFormatException e){
        return false;
    }
    return true;
}

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String expression ;
    System.out.println("Enter an arithmetic expression: ");
    expression  = input.nextLine();
    //for storing integers
    String [] store = new String[100];
    //stack for storing operators
    Stack<String> stack = new Stack<String>();
    //split the string
    String [] tokens = expression.split("");


    for (int i = 0; i <tokens.length; i ++){
        if (isInteger(tokens[i])== true){
            store[i] = tokens[i];

        }
        if (tokens[i] == "+"){
            while (!stack.isEmpty()){
                stack.push(tokens[i]);

            }
            for (int j= 0; j <store.length; j ++){
                int x = Integer.parseInt(store[j]);
                int y = Integer.parseInt(store[j+1]);
                int z = x+y;
                System.out.println(z);
            }               
        }       
    }
}

}

代码不完整,所以看起来有点乱。我试图按照此网页上提供的算法http://www.smccd.net/accounts/hasson/C++2Notes/ArithmeticParsing.html

1 个答案:

答案 0 :(得分:0)

问题是

tokens[i] == "+"

在Java中,'=='比较参考值。它适用于像'int'或'double'这样的原始类型,但是像String或Integer这样的对象类型会变得更复杂。 一个简单的例子:

"+" == "+" // always true
new String("+") == "+" // always false - this is what you are actually doing here
"+".equals(new String("+")) // always true

你想要的实际上是:

"+".equals(tokens[i]) // this will compare the actual value

您要使用的算法还有一件事。我认为您要使用的符号称为Reverse Polish notation。您需要先转换输入 - 维基百科上有一个示例。

相关问题