-3

I am trying to make a program that executes commands. I am splitting commands with space. In a console, if I type (X 2 C) it works as it prints the previous 2 commands and then it Clears all the previous commands. but if I just want to print previous history commands without clearing commands for ex) (X 1) there is a java.lang.ArrayIndexOutOfBoundsException:

Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
Hans Hong
  • 7
  • 2
  • `Split[2]` will only succeed without an `ArrayOutOfBoundsException` if `Split.length > 2`. Did you check that `Split.length > 2` first before just assuming that `Split[2]` would succeed? – Kevin Anderson May 11 '18 at 06:56
  • 2
    What does the error message say? What does your debugger say? – Ken Y-N May 11 '18 at 06:57

2 Answers2

2

Before accessing Split[2] check if Split.length >2

pavithraCS
  • 709
  • 6
  • 23
2

When you input X 1 and split it into an array the resulting array will be ["X" , "1"]. Since Arrays start at 0 the size of the array is 2 with "X" having the index 0 and "1" the index 1.

By attempting to access Split[2] you are trying to access a value which isn't present and an index which is exceeding the length of the array and therefore get an ArrayIndexOutOfBoundsException.

Before tryong to access certain indices you should always make sure that the index you attempt to access is within the size of the array.

L.Spillner
  • 1,772
  • 10
  • 19