Array Index Out Of Bounds - Java

前端 未结 2 693
迷失自我
迷失自我 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;
    

提交回复
热议问题