Array Index Out Of Bounds - Java

前端 未结 2 694
迷失自我
迷失自我 2021-01-24 23:23

I have started to work on my first Java program, which is a simple calculator, however I get an error claiming that my array is out of bounds. I have tried to debug it to see wh

相关标签:
2条回答
  • 2021-01-24 23:53

    When operationIndex is equal to the last element index in outputNum, then operationIndex + 1 will be greater than the last element index: hence your exception

    You would be better off using a for loop that started at index 1, and doing:

    // 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);
      ...
    }
    

    or, alternatively, use your current loop, but do:

      // operationIndex++; // remove this and use ..
      if (++operationIndex >= outputNum.size()) break;
    
    0 讨论(0)
  • 2021-01-25 00:05

    You are only ever adding one item to your list:

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

    Then you try to access what seems to be a second object at index operationindex +1 which doesn't exist:

    answer = outputNum.get(operationIndex) * outputNum.get(operationIndex+1);
    
    0 讨论(0)
提交回复
热议问题