首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >算术表达式解析器

算术表达式解析器
EN

Stack Overflow用户
提问于 2013-11-19 10:05:37
回答 1查看 1.3K关注 0票数 0

我正在尝试实现一个简单的解析器来解决算术表达式,如"(9+7)*(10-4)".Right现在我只是测试我的代码与一些简单的计算,如"9+7“等。它允许用户输入一个字符串,但当我输入表达式并点击回车后,什么也没有发生(控制台中为空白)。以下是我的代码:

代码语言:javascript
复制
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上提供的算法。

EN

回答 1

Stack Overflow用户

发布于 2013-11-19 15:48:09

问题是

代码语言:javascript
复制
tokens[i] == "+"

在Java语言中,“==”比较引用的值。它适用于像“int”或“double”这样的基本类型,但对于像String或Integer这样的对象类型,事情变得更加复杂。一个简单的例子:

代码语言:javascript
复制
"+" == "+" // always true
new String("+") == "+" // always false - this is what you are actually doing here
"+".equals(new String("+")) // always true

你想要的实际上是:

代码语言:javascript
复制
"+".equals(tokens[i]) // this will compare the actual value

关于你想要使用的算法还有一件事。我认为你想要使用的符号叫做Reverse Polish notation。你需要先转换你的输入--维基百科上有一个例子。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20061776

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档