以下代码看起来有些凌乱,但我想不到如何使它更整洁。有任何想法吗? 我想要对值为10、20和30调用doSearch。如果某个值没有返回结果,那么我想尝试下一个值。否则,退出程序。我知道这样可以实现,但这是最易读的方式吗?
SearchResult result = doSearch("10");
if (result.getResults() == null) {
result = doSearch("20");
if (result.getResults() == null) {
result = doSearch("30");
if (result.getResults() == null) {
// put code to deal with lack of results here
}
}
}
i >= attempts.length + 1
没有太多意义,因为它永远不可能评估为真。代码要么会因为ArrayIndexOutOfBounds
而中断,要么检查返回 false。 - Marko Topolnikint i; for (i = 0; i < attempts.length; i++) if ((result = doSearch(attempts[i])) != null) break; if (result == null) // put code to deal with lack of results here
- Marko Topolnikstatic import
,你也可以这样写String attempt : asList("10", "20", "30")
。 - Marko TopolnikInteger.valueOf
以获得WTF效果 :) - Marko Topolnik