【发布时间】: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。
【问题讨论】:
-
您是否使用调试器完成了解析流程?
-
您希望
String [] tokens = expression.split("");为您做什么?
标签: java parsing math arithmetic-expressions