数组索引越界 - Java

Array Index Out Of Bounds - Java

我已经开始编写我的第一个 Java 程序,这是一个简单的计算器,但是我收到一条错误消息,声称我的数组超出范围。我试图调试它以查看它在哪里以及为什么会这样,以及遵循纸上的代码,两者都显示了我期望和希望的结果。因此,我看不出问题到底出在哪里。代码不完整。

根据调试器,错误发生在这一行:

answer = outputNum.get(operationIndex) * outputNum.get(operationIndex+1);

这是我目前拥有的代码的主要部分:

   private class ButtonHandler implements ActionListener {

        /*
         * "outputNum" stores the numbers entered in order.
         * "orderOfOperations" stores all numbers in order after multiplication and division has been taken care of.
         * "operationList" stores the mathematical operations entered in order.
         * "currentNum" stores the most recently inputed numbers.
         * "currentString" stores the most recently inputed string of numbers.
         * "answer" stores temporary values and ultimately the answer to the inputed equation.
         * "start" stores whether or not the equals button has been pressed and a new equation has started.
         */
        ArrayList <Double> outputNum = new ArrayList <Double> (0);
        ArrayList <Double> orderOfOperations = new ArrayList <Double> (0);
        ArrayList <String> operationList = new ArrayList <String> (0);
        Double currentNum = 0.0;
        String currentString = "0";
        Double answer = 0.0;
        boolean start = false;

            public void actionPerformed(ActionEvent event) {

                if(event.getSource() == equalsBtn) {

                    /* Takes the current numbers string and convert it into a double.
                     * Let the order of operations be the inputed order for now.
                     * "operationIndex" to get values inside of the unchanging arrays "outputNum" and "operationList".
                     * "orderIndex" to get values inside of the changing array "orderOfOperations".
                     */
                    currentNum = Double.parseDouble(currentString);
                    outputNum.add(currentNum);
                    orderOfOperations = outputNum;
                    int operationIndex = 0;
                    int orderIndex = 0;

                        //Cycle through the mathematical operations that occur in the current equation.
                        for(String operation : operationList) {

                            if(operation == "x" || operation == "÷") {

                                // Multiply/divide numbers with the multiply/divide operations together.
                                if(operation == "x") {

                                    answer = outputNum.get(operationIndex) * outputNum.get(operationIndex+1);

                                }
                                else {

                                    answer = outputNum.get(operationIndex) / outputNum.get(operationIndex+1);

                                }

                                // Replace numbers multiplied/divided in the above statement with the new answer.
                                orderOfOperations.remove(orderIndex);
                                orderOfOperations.set(orderIndex, answer);
                                orderIndex++;

                            }

                            operationIndex++;

                        }

                    // Reset variables to the default values for the new equation.
                    System.out.println(orderOfOperations);
                    outputString = answer.toString();
                    answer = 0.0;
                    currentNum = 0.0;
                    currentString = "0";
                    outputNum.clear();
                    operationList.clear();
                    orderOfOperations.clear();
                    start = true;

                }
                else if(event.getSource() == additionBtn || event.getSource() == subtractionBtn || event.getSource() == multiplicationBtn || event.getSource() == divisionBtn) {

                    // Sets the text fields text blank if this is the start of a new equation.
                    if(start) {

                        outputString = "";
                        start = false;

                    }

                    /*
                     * Takes the current numbers string and convert it into a double.
                     * Add the mathematical operation and reset the current number.
                     */
                    currentNum = Double.parseDouble(currentString);
                    outputNum.add(currentNum);
                    operationList.add(event.getActionCommand());
                    currentString = "0";
                    outputString = String.format("%s%s", outputString, event.getActionCommand());

                }
                else {

                    // Sets the text fields text blank if this is the start of a new equation.
                    if(start) {

                        outputString = "";
                        start = false;

                    }

                    // Adds the button value to the text field text and the current number being inputed.
                    currentString = String.format("%s%s", currentString, event.getActionCommand());
                    outputString = String.format("%s%s", outputString, event.getActionCommand());

                }

            outputScreen.setText(outputString);

        }

    }

这是我收到的错误消息:

Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
    at java.util.ArrayList.RangeCheck(ArrayList.java:547)
    at java.util.ArrayList.get(ArrayList.java:322)
    at MainWindow$ButtonHandler.actionPerformed(MainWindow.java:141)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.java:6414)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3275)
    at java.awt.Component.processEvent(Component.java:6179)
    at java.awt.Container.processEvent(Container.java:2084)
    at java.awt.Component.dispatchEventImpl(Component.java:4776)
    at java.awt.Container.dispatchEventImpl(Container.java:2142)
    at java.awt.Component.dispatchEvent(Component.java:4604)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4618)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4279)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4209)
    at java.awt.Container.dispatchEventImpl(Container.java:2128)
    at java.awt.Window.dispatchEventImpl(Window.java:2492)
    at java.awt.Component.dispatchEvent(Component.java:4604)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:717)
    at java.awt.EventQueue.access0(EventQueue.java:82)
    at java.awt.EventQueue.run(EventQueue.java:676)
    at java.awt.EventQueue.run(EventQueue.java:674)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext.doIntersectionPrivilege(AccessControlContext.java:86)
    at java.security.AccessControlContext.doIntersectionPrivilege(AccessControlContext.java:97)
    at java.awt.EventQueue.run(EventQueue.java:690)
    at java.awt.EventQueue.run(EventQueue.java:688)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext.doIntersectionPrivilege(AccessControlContext.java:86)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:687)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

operationIndex 等于 outputNum 中的最后一个元素索引时,operationIndex + 1 将大于最后一个元素索引:因此您的例外情况

您最好使用从索引 1 开始的 for 循环,并执行以下操作:

// assuming that operationList and outputNum always 
//   have the same number of elements
for (int i = 1; i < operationList.size(); i++) {
  ...
  answer = outputNum.get(i - 1) * outputNum.get(i);
  ...
}

或者,或者,使用您当前的循环,但是:

  // operationIndex++; // remove this and use ..
  if (++operationIndex >= outputNum.size()) break;

您只会将一项添加到列表中:

currentNum = Double.parseDouble(currentString);
outputNum.add(currentNum);

然后您尝试访问索引 operationindex +1 处似乎不存在的第二个对象:

answer = outputNum.get(operationIndex) * outputNum.get(operationIndex+1);