javacoderunner

java.lang.ArrayIndexOutOfBoundsException why am i getting this


Why am i getting the exception error

va.lang.ArrayIndexOutOfBoundsException why am i getting thisva.lang.ArrayIndexOutOfBoundsException why am i getting thisva.lang.ArrayIndexOutOfBoundsException why am i getting thisva.lang.ArrayIndexOutOfBoundsException why am i getting thisva.lang.ArrayIndexOutOfBoundsException why am i getting thisva.lang.ArrayIndexOutOfBoundsException why am i getting thisva.lang.ArrayIndexOutOfBoundsException why am i getting thisva.lang.ArrayIndexOutOfBoundsException why am i getting thisva.lang.ArrayIndexOutOfBoundsException why am i getting thisva.lang.ArrayIndexOutOfBoundsException why am i getting thisva.lang.ArrayIndexOutOfBoundsException why am i getting this

}

Solution

  • You wrote 'a'-'z' which will convert into ASCII code subtraction and the result will be -25, and as for your 'A'-'Z' statement, the result will be (well, also) -25.

    You should write something like

    if( (chr <= 'z' && chr >= 'a') || (chr <= 'Z' && chr >= 'A') )
        return true;
    return false;
    

    Always remember, that computers work with ASCII codes, rather than "characters", and the computer will check for the valid code of given characters (which are always positive, -25 is not valid), in our case, the ASCII code of chr SHOULD be smaller-or-equal to z, and so on (see the if-statement above).

    If you are familiar with overloading the return statement, you could also simplify your function (make it more readable):

    return (chr >= 'a' && chr <= 'z') || (chr >= 'A' && chr <= 'Z')