有没有办法让while循环稍微优化一下。特别令我烦恼的是,我必须在if条件内外重复代码(关闭缓冲区并返回值),我想知道是否有更好/更多以性能为导向的方法来处理这样的代码。
while ((line = buf.readLine()) != null) {
// Get a random line number
if (currLine == lineToFetch) {
quote = line;
Log.v("LINE", line);
randomQuote.close();
buf.close();
return quote;
} else {
currLine++;
}
}
randomQuote.close();
buf.close();
return quote;
答案 0 :(得分:4)
因为你打电话给close()
而你返回quote
无论你找到了什么或不是你的线路,你都可以把它变得更好:
while ((line = buf.readLine()) != null && currLine != lineToFetch) {
currLine++;
}
if (currLine == lineToFetch){
quote = line;
}
randomQuote.close();
buf.close();
return quote;
答案 1 :(得分:1)
您可以使用finally
块来简化它 -
try {
while ((line = buf.readLine()) != null) {
// Get a random line number
if (currLine == lineToFetch) {
quote = line;
Log.v("LINE", line);
break;
} else {
currLine++;
}
}
} finally {
randomQuote.close();
buf.close();
}
return quote;
答案 2 :(得分:0)
您只需使用break
退出循环,然后依赖函数末尾的清理代码:
while ((line = buf.readLine()) != null) {
// Get a random line number
if (currLine == lineToFetch) {
quote = line;
Log.v("LINE", line);
break;
} else
currLine++;
}
randomQuote.close();
buf.close();
return quote;
答案 3 :(得分:0)
基本上,当你找到引用时退出while循环:
foundQuote = false;
while ((line = buf.readLine()) != null && !foundQuote ) {
// Get a random line number
if (currLine == lineToFetch) {
quote = line;
foundQuote = true;
} else
currLine++;
}
randomQuote.close();
buf.close();
return quote;
答案 4 :(得分:0)
您可以直接读取线条,直到找到所需的线条。如果你找到了,那么line将是非null。
while ((line = buf.readline()) != null && curLine < lineToFetch)
curLine++;
// make sure we've found the line
if ( line != null) {
quote = line;
Log.v("LINE", line );
}
randomQote.close();
buf.close();
return quote;