指令赋一个值,但该值不被任何后续指令读取或使用



我有一段代码

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[] randomms = new String[4];"

该指令将一个值赋给一个局部变量,但该值不会被任何后续指令读取或使用。通常,这表示一个错误,因为计算的值永远不会被使用。

为什么我得到这个?

Thanks to lot

因为您将变量初始化为一个值(new String[4]),然后将变量值替换为另一个值(str.split(",")的结果)。因此不需要初始化。

你的代码在功能上等同于

String[] randoms = str.split(",");

,除非它分配一个新的String数组,该数组立即被丢弃。

因为你可以这样做:

String[] randoms = str.split(",");

直接尝试:

String[] randoms = str.split(",");

不需要实例化String[], split方法已经实例化了

这是一个我称之为的技巧的例子。

通常是程序员写代码,但不知道他们在做什么。程序员有时会读到或听到这样的话:"必须初始化所有局部变量!"当他们写代码String[] randoms时,他们突然想到了= new String[4]

一个更有经验的程序员可能会看到这一点,并认为我曾经是愚蠢的,但现在不再了!让我们将变量声明移出循环并生成如下内容:<>之前的字符串str;String[]随机;For (int index = 0;指数& lt;num_of_random;+ +指数){str = in.readLine();If (str != null){随机= str.split(",");dateRanges[index] = Integer.parseInt(random [0]);id[index] = Integer.parseInt(random [1]);flag[index] = Integer.parseInt(random [2]);system[index] = Integer.parseInt(random [3]);}}

相关内容

最新更新