Reputation:
the following method has been marked by my IDE as having too high cyclomatic complexity. I'm required by my school to eliminate all warnings my IDE might throw up in my code, so I'm wondering if there's an easy way to do it in such a case.
For context, the code is supposed to select which column of fields on a playing board with columns labeled A to O a given char represents.
public int getColumn(final char c) {
switch (c) {
case 'A':
return 0;
case 'B':
return 1;
case 'C':
return 2;
case 'D':
return 3;
case 'E':
return 4;
case 'F':
return 5;
case 'G':
return 6;
case 'H':
return 7;
case 'I':
return 8;
case 'J':
return 9;
case 'K':
return 10;
case 'L':
return 11;
case 'M':
return 12;
case 'N':
return 13;
case 'O':
return 14;
default:
return -1;
}
}```
Upvotes: 0
Views: 653
Reputation: 639
Can do it using map:
Map<Character, Integer> columnMap = ImmutableMap
.of('A', 0, 'B', 1, 'C',3);//Or any other initialization way
public int getColumn(final char c) {
return columnMap.getOrDefault(c, -1);//-1 default value if letter not found
}
Or, if you just want to get the capital letter's position in the alphabet, use this:
public int getColumn(final char c) {
return (int)c - 'A';
}
Upvotes: 0
Reputation: 141
I'm not sure if that would work in your context, but why not just use the ASCII characters table?
You could cast it to an integer, and since the uppercase A character is index 65, you can just subtract 65 from it.
For example:
public int getColumn(final char c) {
int index = (int) c;
if (index > (int) 'O') {
return -1;
}
return index - (int) 'A';
}
Upvotes: 0
Reputation: 1561
Alternatively abuse the fact that a character is represented as a numeric:
public int getColumn(final char c) {
if((c >= 'A') && (c <= 'O')) {
return c - 'A';
}
else {
return -1;
}
}
Upvotes: 2
Reputation: 313
Use a hashmap to store character as key and number as value.
refer https://www.w3schools.com/java/java_hashmap.asp for usage of hashmap
Upvotes: 1