Java 算术表达式解析器

Java 算术表达式解析器,java,parsing,math,arithmetic-expressions,Java,Parsing,Math,Arithmetic Expressions,我正在尝试实现一个简单的解析器来解决算术表达式,例如 “(9+7)*(10-4)”。现在我只是用一些简单的计算来测试我的代码,如“9+7”等。它允许用户输入字符串,但在我输入表达式并单击enter后,什么都没有发生(控制台中为空)。这是我的密码: public class parser { //check whether if a string is an integer public static boolean isInteger (String s){ try{

我正在尝试实现一个简单的解析器来解决算术表达式,例如 “(9+7)*(10-4)”。现在我只是用一些简单的计算来测试我的代码,如“9+7”等。它允许用户输入字符串,但在我输入表达式并单击enter后,什么都没有发生(控制台中为空)。这是我的密码:

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);
            }               
        }       
    }
}

}
公共类解析器{
//检查字符串是否为整数
公共静态布尔isInteger(字符串s){
试一试{
整数.parseInt(s);
}捕获(数字格式){
返回false;
}
返回true;
}
公共静态void main(字符串[]args){
扫描仪输入=新扫描仪(System.in);
字符串表达式;
System.out.println(“输入一个算术表达式:”);
expression=input.nextLine();
//用于存储整数
字符串[]存储=新字符串[100];
//用于存储运算符的堆栈
堆栈=新堆栈();
//拆线
String[]tokens=expression.split(“”);
对于(inti=0;i是,问题是

tokens[i] == "+"
在Java中,“==”比较参考值。它适用于诸如“int”或“double”之类的基本类型,但对于诸如字符串或整数之类的对象类型,事情会变得更复杂。 一个简单的例子:

"+" == "+" // 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

关于您要使用的算法还有一点。我认为您要使用的符号被调用了。您需要首先转换您的输入-wikipedia上有一个示例。

您是否使用调试器完成了解析流程?看看您希望
String[]tokens=expression.split(“”;
为您做什么?