gpt4 book ai didi

java - 如何解决 for-loop 中的 SonarQube 提示者?

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:08:22 24 4
gpt4 key购买 nike

我编写了一个方法,将字节从 InputStream 复制到 OutputStream

// copies bytes from given input stream to specified output stream
// returns the number of bytes copied.
private static long copy(final InputStream input,
final OutputStream output)
throws IOException {
long count = 0L;
final byte[] buffer = new byte[4096];
for (int length; (length = input.read(buffer)) != -1; count += length) {
output.write(buffer, 0, length);
}
return count;
}

SonarQube 提示。

This loop's stop condition tests "length, input, buffer" but the incrementer updates "count".

It is almost always an error when a for loop's stop condition and incrementer don't act on the same variable. Even when it is not, it could confuse future maintainers of the code, and should be avoided.

对于相同的目的,是否有更好的代码?

更新

按照建议的答案,我确实喜欢这个,问题消失了。

// copies bytes from given input stream to specified output stream
// returns the number of bytes copied.
private static long copy(final InputStream input,
final OutputStream output)
throws IOException {
long count = 0L;
final byte[] buffer = new byte[4096];
for (int length; (length = input.read(buffer)) != -1;) {
output.write(buffer, 0, length);
count += length;
}
return count;
}

最佳答案

您正在滥用 for 循环,这就是 SonarQube 发出警告的原因。在下面的循环中,您在更新子句中递增 count 但停止条件不依赖于 count

for (int length; (length = input.read(buffer)) != -1; count += length) {
^---------------------------------^ ^-------------^
does not depend on count increments count

相反,您应该使用 while 循环并在循环体内递增计数:

private static long copy(final InputStream input, final OutputStream output) throws IOException {
long count = 0;
final byte[] buffer = new byte[4096];
int length;
while ((length = input.read(buffer)) != -1) {
output.write(buffer, 0, length);
count += length;
}
return count;
}

关于java - 如何解决 for-loop 中的 SonarQube 提示者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35719682/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com