我有这些长长的声明,我将在这里称为x,y等。我的条件语句的结构如下:
if(x || y || z || q){
if(x)
do someth
else if (y)
do something
if(z)
do something
else if(q)
do something
}
else
do smthing有没有更好、更短的方法来写这个东西呢?谢谢
发布于 2010-04-07 15:17:59
这对我来说似乎很清楚(清楚就好了)。
你可以做的是首先计算x,y,z和q,并将它们存储为变量,这样你就不需要做两次了。
发布于 2010-04-07 15:22:12
我看不出你现在怎么写有什么大问题。我建议使用大括号,即使是单语句if块也是如此。这将帮助您避免错误,以防您必须添加更多的代码行(然后可能会忘记添加大括号)。我也发现它的可读性更好。然后,代码将如下所示:
if (x || y || z || q) {
if (x) {
do something
} else if (y) {
do something
}
if (z) {
do something
} else if (q) {
do something
}
} else {
do something
}发布于 2010-04-07 15:24:28
另一个避免多次检查和容易出错的复杂逻辑表达式的变体可能是:
boolean conditionhandled = false;
if (x) {
do something
conditionhandled = true;
} else if (y) {
do something
conditionhandled = true;
}
if (z) {
do something
conditionhandled = true;
} else if (q) {
do something
conditionhandled = true;
}
if (!conditionhandled) {
do something
}https://stackoverflow.com/questions/2590595
复制相似问题