【问题标题】:parser for arithmetic expressions算术表达式解析器
【发布时间】:2013-12-02 10:17:45
【问题描述】:

我正在尝试实现一个简单的解析器来解决算术表达式,例如 “(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

【问题讨论】:

标签: java parsing math arithmetic-expressions


【解决方案1】:

是不是问题是

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。您需要先转换您的输入 - 维基百科上有一个示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 2022-09-26
    • 2011-01-25
    • 2015-12-20
    相关资源
    最近更新 更多