java中使用switch块代替多个if语句
public class A {
public void search(boolean[] searchList) {
// searchList array is used to identify what options to search for in a given order
// e.g. boolean [] searchList = new boolean [] {false, false, true, false};
boolean searchL = false;
boolean searchM = false;
boolean searchK = false;
boolean searchA = false;
if(searchList[0] == true) searchL = true;
if(searchList[1] == true) searchM = true;
if(searchList[2] == true) searchK = true;
if(searchList[3] == true) searchA = true;
if(searchL == true) // write a query to search for all Ls
if(searchM == true) // write a query to search for all Ms
...........
}
有没有办法可以简化这段代码?
@All:抱歉之前发布了错误的问题。我很困惑!
谢谢, 索尼
public class A {
public void search(boolean[] searchList) {
// searchList array is used to identify what options to search for in a given order
// e.g. boolean [] searchList = new boolean [] {false, false, true, false};
boolean searchL = false;
boolean searchM = false;
boolean searchK = false;
boolean searchA = false;
if(searchList[0] == true) searchL = true;
if(searchList[1] == true) searchM = true;
if(searchList[2] == true) searchK = true;
if(searchList[3] == true) searchA = true;
if(searchL == true) // write a query to search for all Ls
if(searchM == true) // write a query to search for all Ms
...........
}
Is there a way I can simplify this code ?
@All : Sorry for posting a wrong question before. I was confused!
Thanks,
Sony
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我是枚举的忠实粉丝:
另请注意:您的场景允许一次有多个搜索布尔值为真,我认为这不是您的目标,但如果是的话,我们可以稍微调整一下。
I am a big fan of enums:
note also: your scenario allowed more than one search boolean to be true at a time, I assumed that was not your goal, but if it is we can tweak this a bit.
您应该将您的状态转换为枚举。例如,您的搜索布尔值似乎是排他性的,所以我会做这样的事情:
如果您的状态不是排他性的,您应该尝试构建以最初构建一组排他性状态的超级集。
You should convert your state into an enum. For example your search booleans seem to be exclusive so i would do something like this:
If your states aren't exclusive you should try build to build a super set of exclusive states initially.
为什么不采用OOP?喜欢:
Why don't employ OOP? Like:
根据您的评论,这是我对该方法的更新示例 - 确保顶部的评论已更新!
最新想法:
As per your comment, here's my updated example of that method - make sure the comment at the top is updated!
Latest idea:
像这样: ?
}
Like this: ?
}