降低 switch 语句的圈复杂度
Reducing cyclomatic complexity of a switch statement
以下方法已被我的 IDE 标记为圈复杂度过高。我的学校要求我消除我的 IDE 可能在我的代码中抛出的所有警告,所以我想知道在这种情况下是否有一种简单的方法来做到这一点。
对于上下文,代码应该 select 给定字符代表 A 到 O 列的游戏板上的哪一列字段。
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;
}
}```
使用哈希映射将字符存储为键,将数字存储为值。
的用法
或者滥用字符表示为数字的事实:
public int getColumn(final char c) {
if((c >= 'A') && (c <= 'O')) {
return c - 'A';
}
else {
return -1;
}
}
可以使用地图完成:
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
}
或者,如果您只想获得大写字母在字母表中的位置,请使用:
public int getColumn(final char c) {
return (int)c - 'A';
}
我不确定这是否适用于您的上下文,但为什么不只使用 ASCII 字符 table?
您可以将其转换为整数,并且由于大写字母 A 的索引为 65,因此您只需从中减去 65。
例如:
public int getColumn(final char c) {
int index = (int) c;
if (index > (int) 'O') {
return -1;
}
return index - (int) 'A';
}
以下方法已被我的 IDE 标记为圈复杂度过高。我的学校要求我消除我的 IDE 可能在我的代码中抛出的所有警告,所以我想知道在这种情况下是否有一种简单的方法来做到这一点。
对于上下文,代码应该 select 给定字符代表 A 到 O 列的游戏板上的哪一列字段。
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;
}
}```
使用哈希映射将字符存储为键,将数字存储为值。
的用法或者滥用字符表示为数字的事实:
public int getColumn(final char c) {
if((c >= 'A') && (c <= 'O')) {
return c - 'A';
}
else {
return -1;
}
}
可以使用地图完成:
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
}
或者,如果您只想获得大写字母在字母表中的位置,请使用:
public int getColumn(final char c) {
return (int)c - 'A';
}
我不确定这是否适用于您的上下文,但为什么不只使用 ASCII 字符 table?
您可以将其转换为整数,并且由于大写字母 A 的索引为 65,因此您只需从中减去 65。
例如:
public int getColumn(final char c) {
int index = (int) c;
if (index > (int) 'O') {
return -1;
}
return index - (int) 'A';
}