小编典典

数组索引超出范围-Java

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.access$400(EventQueue.java:82)
    at java.awt.EventQueue$2.run(EventQueue.java:676)
    at java.awt.EventQueue$2.run(EventQueue.java:674)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:86)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:690)
    at java.awt.EventQueue$3.run(EventQueue.java:688)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.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)

阅读 487

收藏
2020-11-26

共1个答案

小编典典

operationIndex等于中的最后一个元素索引时outputNumoperationIndex + 1则将大于最后一个元素索引:因此,您的异常

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

// 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;
2020-11-26