【发布时间】:2017-05-16 11:25:13
【问题描述】:
我正在尝试使用 JavaFX 和反向波兰表示法创建一个计算器。想法是使用 TextField 读取用户的输入,然后将常见的中缀形式转换为后缀形式,进行计算并通过按下“等于”按钮呈现输出。我希望它能够对双打进行操作。取自用户的示例公式是:
((234*(7-3))/2)
转换为后缀形式后应如下所示:234 7 3 - * 2 /
经过一些麻烦,我设法做到了,但只是作为使用控制台的测试。
当我将它与之前构建的 JavaFX GUI 连接时,它会抛出 RunTime 异常,我不知道它为什么会发生。所以,我将字符串标记存储在一个 ArrayList 中,这是我的解析方法:
public void parseExpression(String expr) {
char[] temp = expr.toCharArray();
StringBuffer stringBuffer = new StringBuffer();
List<String> list = new ArrayList<String>();
for (int i=0;i<temp.length;i++) {
if(temp[i]=='(' || temp[i]==')' || temp[i]=='+' || temp[i]=='-' || temp[i]=='*' || temp[i]=='/') {
list.add(Character.toString(temp[i]));
} else{
stringBuffer.append(temp[i]);
if ((i+1)<temp.length){
if (temp[i+1]=='(' || temp[i+1]==')' || temp[i+1]=='+' || temp[i+1]=='-' || temp[i+1]=='*' || temp[i+1]=='/'){
String number = stringBuffer.toString();
stringBuffer.setLength(0);
list.add(number);
}
}
}
}
for (String str: list){
System.out.print(str+" ");
}
}
我的后缀转换方法是这样的:
public void beginConvert(){
convertToONP(list.get(0));
}
public void convertToONP(String current) {
if (currIndex < list.size()) {
String a;
String c = current;
if (c.equals("(")) {
convertToONP(list.get(++currIndex));
a = list.get(currIndex);
convertToONP(list.get(++currIndex));
++currIndex;
System.out.print(a+" ");
} else {
System.out.print(c+" ");
++currIndex;
}
}
}
当我在测试类中运行这些方法时:
public class Test {
/*
*my methods methods
*/
public static void main(String[] args) {
Test test = new Test();
String formula = "(234+(2*3))";
test.parseExpression(formula);
System.out.println();
test.beginConvert();
}
}
这是输出:
( 234 + ( 2 * 3 ) )
234 2 3 * +
但是当我将这些方法放在连接到 FXML 文件的控制器类中的按钮的 setOnAction 方法中时:
@FXML
public void equalsPressed(){
calculator.parseExpression(formulaTextField.getText());
calculator.beginConvert();
}
这是输出:
( 234 + ( 2 * 3 ) )
线程“JavaFX 应用程序线程”中的异常 java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
引起:java.lang.IndexOutOfBoundsException:索引:0,大小:0
在model.Calculator.beginConvert(Calculator.java:60)
有人可以向我解释为什么会这样吗?非常感谢您提供的任何帮助
【问题讨论】:
标签: java javafx postfix-notation