我想根据数字范围编写一个switch语句:
1 <= x <= 4: index = 1
5 <= x <= 7: index = 2
8 <= x <= 10: index = 3
(more to come)
基于范围x
我想设置索引
除了嵌套if-else语句之外,我能做得更好吗?
if (number > 0 && number < 5) {
index = 1;
} else if (number > 4 && number< 8) {
index = 2;
} else if (number > 7 && number < 11) {
index = 3;
}
答案 0 :(得分:1)
将规则保存在单个数组中的另一个想法。
如果你有大量的范围和索引要处理,可以很方便。
//Rules as an array of [from, to, index] definitions
int[][] rules = {
{ 1, 4, 1 },
{ 5, 7, 2 },
{ 8, 10, 3 }
};
for (int[] rule : rules)
{
if ((number >= rule[0]) && (number <= rule[1])) {
index = rule[2];
break;
}
}