Findbugs java中可能的空指针取消引用

时间:2016-10-04 04:18:55

标签: java nullpointerexception findbugs dereference

我正在使用FindBugs来检测代码包含的错误。我找到了一些bug的解决方案,但是,我无法理解为什么它仍然在检查“micro”的行中显示“可能的空指针解除引用”错误。在while循环中,我已经显示我的输入应该与null值不同,但是,它仍然显示bug存在。如果可能的话,你能说出如何解决这个问题吗?提前致谢!代码如下:

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;


public class FindBug {

    public static void main(String args[]) 

    {


        InputStreamReader reader = new InputStreamReader(System.in,Charset.defaultCharset());
        BufferedReader bufferedreader = new BufferedReader(reader);

        String scan = null;

        boolean nextfound=false;

        try 
        {
           while(null!=(scan= bufferedreader.readLine())&&nextfound)

            {
              scan=scan.replace('i', 'a');

            }
        } 
        catch (IOException ioex) 
        {
            System.err.println(ioex.getMessage());
        }

        if (scan.equals("micro")) 
        {
            System.out.println("The result is macro!");
        } 


        else

        {
            System.out.println("Something else!");
        }
    }
}

2 个答案:

答案 0 :(得分:4)

scan可以是null,也许您可​​以简单地反转您的测试

if ("micro".equals(scan){
   System.out.println("The result is Macro!")
}

还有一些错误:

scan=scan.replace('i', 'a');永远不会被执行,因为nextfound始终是false

while(null!=(scan= bufferedreader.readLine())&&nextfound)
{
    scan=scan.replace('i', 'a');
}

bufferReader永远不会关闭您应该在代码中添加finally

...
catch (IOException ioex) {
    System.err.println(ioex.getMessage());
} finally {
    try {
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

答案 1 :(得分:0)

如果输入为空,则不会执行while循环。 scan将设为null,瞧,NullPointerException

相关问题