简体   繁体   English

降低 switch 语句的圈复杂度

[英]Reducing cyclomatic complexity of a switch statement

the following method has been marked by my IDE as having too high cyclomatic complexity.以下方法已被我的 IDE 标记为具有太高的圈复杂度。 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.我的学校要求我消除我的代码中可能出现的 IDE 的所有警告,所以我想知道在这种情况下是否有一种简单的方法可以做到这一点。

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.对于上下文,代码应该是 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;
        }
    }```

Use a hashmap to store character as key and number as value.使用 hashmap 将字符存储为键,将数字存储为值。

refer https://www.w3schools.com/java/java_hashmap.asp for usage of hashmap有关 hashmap 的用法,请参阅https://www.w3schools.com/java/java_hashmap.asp

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;
    }
}

Can do it using map:可以使用 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:或者,如果您只想在字母表中获取大写字母的 position,请使用以下命令:

public int getColumn(final char c) {
    return (int)c - 'A';
}

I'm not sure if that would work in your context, but why not just use the ASCII characters table?我不确定这是否适用于您的上下文,但为什么不直接使用 ASCII 字符表呢?

You could cast it to an integer, and since the uppercase A character is index 65, you can just subtract 65 from it.您可以将其转换为 integer,并且由于大写 A 字符的索引为 65,因此您只需从中减去 65。

For example:例如:

public int getColumn(final char c) {
    int index = (int) c;

    if (index > (int) 'O') {
        return -1;
    }

    return index - (int) 'A';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM