[英]Unused local variable false positive
While using sonar lint version 6.3.0.39716, it reports the following variable as unused.使用 sonar lint 版本 6.3.0.39716 时,它会将以下变量报告为未使用。
void read() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s; // unused local variable 's'
while ((s = reader.readLine()) != null) {
}
}
But the variable s
is used in the next line, should this be considered as unused as s
is just assigned a value?但是变量s
在下一行中使用,这是否应该被视为未使用,因为s
只是分配了一个值?
Edit- This is not considered an unused local variable.编辑 - 这不被视为未使用的局部变量。
void read() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s; // ok
s = reader.readLine();
while (s != null) {
s = reader.readLine();
}
}
Here also s is just assigned value apart from being used in a boolean condition which it is used in the above case also.除了在上述情况下使用的 boolean 条件之外,这里 s 也只是赋值。
For this code对于此代码
void read() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s; // unused local variable 's'
while ((s = reader.readLine()) != null) {
}
}
The variable s
can be removed completely without side effects as shown below.变量s
可以完全删除而没有副作用,如下所示。
void read() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while ((reader.readLine()) != null) {
}
}
This is why these code analyzers will point out that the variable in question is never used.这就是为什么这些代码分析器会指出所讨论的变量从未使用过。 Setting a value in a variable is not enough to deem a variable as "used".在变量中设置值不足以将变量视为“已使用”。 In the second snippet, the variable s
can't be removed because it is used to make a decision:在第二个片段中,变量s
不能被删除,因为它用于做出决定:
while (s != null) {...}
Because of the line above, removing the variable will result in a compilation error.由于上面的行,删除变量将导致编译错误。 Therefore, the variable is an important part of the code.因此,变量是代码的重要组成部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.