我正在尝试创建一个可以执行简单操作的计算器,并且您应该能够拥有多个值和不同的运算符。它还没有完成,所以稍后会改进,但现在我对执行计算的方法有疑问。
在我发布相关代码之前。另一部分只是 Swing 对象实例化。
private class OperatorListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource()== resetButton){
Operators.clear();
Numbers.clear();
actualNumber.setText("");
previousNumbers.setText("");
} else if(e.getSource() == sumButton){
Numbers.add(new Double(actualNumber.getText()));
Double Result = performCalculation(Numbers, Operators);
actualNumber.setText(String.valueOf(Result));
previousNumbers.setText("");
} else if(e.getSource() == sqrtButton){
} else {
/*
* The operator numbers handlers. When a operator
* button is clicked the number in the lower JTF
* is parsed to Double value and added to Numbers
* list. Operator added to Operators list. Lower
* JTF is cleared.*/
Numbers.add(new Double(actualNumber.getText()));
Operators.add(e.getActionCommand());
String currentPriovusNumbers = previousNumbers.getText();
previousNumbers.setText(currentPriovusNumbers + " " + actualNumber.getText() + " " + e.getActionCommand());
actualNumber.setText("");
}
}
}
private double performCalculation(ArrayList<Double> Numbers, ArrayList<String> Operators){
double result = Numbers.get(0);
for(int index = 0; index < Numbers.size(); index++){
switch(Operators.get(index)){
case "+":
result += Numbers.get(index + 1);
break;
case "-":
result -= Numbers.get(index + 1);
break;
case "/":
result /= Numbers.get(index + 1);
break;
case "*":
result *= Numbers.get(index + 1);
break;
case "%":
result %= Numbers.get(index + 1);
break;
}
}
return result;
}
我得到的错误是:
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(ArrayList.java:604)
at java.util.ArrayList.get(ArrayList.java:382)
at com.calculatorSwing.business.Calculator.performCalculation(Calculator.java:146)
at com.calculatorSwing.business.Calculator.access$6(Calculator.java:143)
第 146 行是第一个 switch case 语句,它让我知道没有我尝试访问的索引,但我检查了 Operators 列表并且元素 0 内有一个“+”。问题是什么?