gpt4 book ai didi

java - 如何修复多个 If-Else 条件下的 SonarLint 认知复杂性错误

转载 作者:行者123 更新时间:2023-12-05 03:17:39 25 4
gpt4 key购买 nike

我要写很多条件,但是 SonarLint 给我报错,要求重构方法以降低其认知复杂度。

如何解决这个问题。我尝试了 switch-case,但这也给出了同样的错误。

public enum ExampleEnum {
UNKNOWN(-1),
D0_D100(0),
D100_D200(100),
D200_D300(200),
D300_D400(300),
D400_D500(400),
D500_D600(500),
D600_D700(600),
D700_D800(700),
D800_D900(800),
D900_D1000(900);

private int score;

ExampleEnum(int score) {
this.score = score;
}
}

public static ExampleEnum getScoreType(Integer score) {
if (Objects.isNull(score) || score < D0_D100.score) {
return UNKNOWN;
} else if (score >= D0_D100.score && score < D100_D200.score) {
return D0_D100;
} else if (score >= D100_D200.score && score < D200_D300.score) {
return D100_D200;
} else if (score >= D200_D300.score && score < D300_D400.score) {
return D200_D300;
} else if (score >= D300_D400.score && score < D400_D500.score) {
return D300_D400;
} else if (score >= D400_D500.score && score < D500_D600.score) {
return D400_D500;
} else if (score >= D500_D600.score && score < D600_D700.score) {
return D500_D600;
} else if (score >= D600_D700.score && score < D700_D800.score) {
return D600_D700;
} else if (score >= D700_D800.score && score < D800_D900.score) {
return D700_D800;
} else if (score >= D800_D900.score && score < D900_D1000.score) {
return D800_D900;
} else {
return D900_D1000;
}
}

最佳答案

将逻辑放入循环中。像这样的东西:

public static ExampleEnum getScoreType(Integer score) {
if (Objects.isNull(score) || score < D0_D100.score) {
return UNKNOWN;
for (int i =0; i< ExampleEnum.values().length-1;i++) {
if (ExampleEnum.values()[i].score <= score && ExampleEnum.values()[i+1].score > score )
return ExampleEnum.values()[i];
}
return D900_D1000;
}

关于java - 如何修复多个 If-Else 条件下的 SonarLint 认知复杂性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74050816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com