I am trying to create a method in java that would tell whether string is well formed. Each character in a string should be equal to one of the pre-defined characters and nothing else. First character should be equal to one of the values in first array. Second character should be equal to one of the values in columns array. Third character should be equal to one of the values in rows array. Fourth character should be equal to one of the values in fourth array. I have this code so far.
public static boolean formedGoodOrNot(String input) {
char[] first = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'};
int[] columns = {1, 2, 3, 4, 5, 6, 7, 8};
char[] rows = {'A', 'B', 'C', 'D'};
int[] fourth = {0, 1, 2, 3, 4, 5, 6, 7};
if(input.length()==4) {
for (int j = 0; j < first.length+1; ) {
for (int k = 0; k < columns.length+1; ) {
for (int l = 0; l < rows.length+1; ) {
for (int m = 0; m < fourth.length+1; ) {
if (input.charAt(0) == first[j]) {
if (input.charAt(1) == columns[k]) {
if (input.charAt(2) == rows[l]) {
if (input.charAt(3) == fourth[m]) {
return true;
} else{
m++;
}
} else {
l++;
}
} else{
k++;
}
} else{
j++;
}
}
}
}
}
} else{
return false;
}
return false;
}
However, it gives me an error
java.lang.ArrayIndexOutOfBoundsException: 12
What is wrong here?
Thank you
You should use regex for this purpose! The regex matching this pattern is :
^[a-l][1-8][A-D][0-7]$
Now you just gotta plug this into a function :
private static final Pattern PATTERN = Pattern.compile("^[a-l][1-8][A-D][0-7]$");
public boolean formedGoodOrNot(String input) {
return PATTERN.matcher(input).matches();
}
and there you go, much more readable and short than your implementation!
To understand how this regex works, please check out this link that explains it : https://regex101.com/r/SDlnzi/1/