指令分配一个值,但该值不会在任何后续指令中读取或使用
我有一段代码
for(int i = 0; i < num_of_random; i++){
String str = in.readLine();
if(str != null){
String[] randoms = new String[4];
randoms = str.split(",");
dateRanges[i] = Integer.parseInt(randoms[0]);
id[i] = Integer.parseInt(randoms[1]);
flag[i] = Integer.parseInt(randoms[2]);
system[i] = Integer.parseInt(randoms[3]);
}
}
的建议
当我针对 findBugs 运行这段代码时,我得到了“String[] randoms = new String[4];”
该指令将一个值分配给局部变量,但该值不会在任何后续指令中读取或使用。通常,这表示错误,因为计算出的值从未被使用过。
为什么我会得到这个?
多谢
I have a piece of code
for(int i = 0; i < num_of_random; i++){
String str = in.readLine();
if(str != null){
String[] randoms = new String[4];
randoms = str.split(",");
dateRanges[i] = Integer.parseInt(randoms[0]);
id[i] = Integer.parseInt(randoms[1]);
flag[i] = Integer.parseInt(randoms[2]);
system[i] = Integer.parseInt(randoms[3]);
}
}
When I run this code against findBugs, I get a suggestion for
"String[] randoms = new String[4];"
This instruction assigns a value to a local variable, but the value is not read or used in any subsequent instruction. Often, this indicates an error, because the value computed is never used.
Why do I get this?
Thanks a lot
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为您将变量初始化为一个值 (
new String[4]
),然后将变量值替换为另一个值(str.split(",")
的结果>) 就在之后。因此初始化是不必要的。您的代码在功能上等同于,
只不过它分配了一个新的 String 数组,该数组立即被丢弃。
Because you initialize a variable to a value (
new String[4]
), and then replace the variable value with another one (the result ofstr.split(",")
) just after. The initialization is thus not necessary.Your code is functionally equivalent to
except it allocates a new String array which is immediately discarded.
因为你可以简单地这样做:
Because you can simply do this:
直接尝试:
您不需要实例化
String[]
,split
方法已经做到了。Try directly:
You don't need to instanciate a
String[]
, thesplit
method already does it.这是我称之为“我很笨”技术的一个例子。
通常,这是程序员编写代码但不理解他们在做什么的结果。在某些时候,程序员读到或听到这样的话:“你必须初始化所有局部变量!”。当他们编写代码时,
String[] randoms
突然出现在他们的脑海中,因此他们添加了= new String[4]
。经验丰富的程序员可能会认为我曾经很愚蠢,但现在不再了!让我们将变量声明移出循环并生成如下内容:
This is an example of the technique that I call The I'm dumb technique.
Typically it is the result of a programmer writing code, but not understanding what they are doing. At some point the programmer read or heard something like this: "you must initialize all local variables!". When they wrote the code
String[] randoms
that popped into their head so they added= new String[4]
.A more seasoned programmer might look at that and think I used to be dumb, but not any more! Lets move the variable declarations out of the loop and produce something like this: