'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 1:[1]

The syntax if(chr == 'a'-'z') is not correct. 'a' and 'z' are both character literals, but in Java a character is a 16-bit integral type. So 'a'-'z' is a long way to write -25. I would simplify the logic and the test. Something like

public static boolean isValidChar_Q1(char chr) {
    char t = Character.toLowerCase(chr);
    return t >= 'a' && t <= 'z';
}

Solution 2:[2]

In your comparisons you're trying to compare a single char to a range, which is something you cannot write like that in Java. That syntax of yours looks closer to a regex ([a-zA-Z]) than a proper Java comparison.

If you want to check whether a variable's value is within a range, you need to compare it with its boundaries: greater than or equal to the left edge and lower than or equal to the right edge.

public static boolean isValidChar_Q1(char chr) {
    return (chr >= 'a' && chr <= 'z') || (chr >= 'A' && chr <= 'Z');
}

Solution 3:[3]

Solution using Regex:

import java.util.regex. * ;

    boolean isMatch = Pattern.matches("[a-zA-Z]", "S");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Elliott Frisch
Solution 2 Dan
Solution 3 Eskandar Abedini