我正在尝试实现一个简单的解析器来解决算术表达式,如"(9+7)*(10-4)".Right现在我只是测试我的代码与一些简单的计算,如"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上提供的算法。
发布于 2013-11-19 15:48:09
问题是
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。你需要先转换你的输入--维基百科上有一个例子。
https://stackoverflow.com/questions/20061776
复制相似问题