java,try 块在操作来自 try 作用域之上的作用域的变量时产生错误

java, try block produces an error while manipulating a variable coming from the scope above try's scope

我在 try 块外声明了一个 BufferedImage,并在其中初始化它。但这似乎不起作用,因为编译器正在考虑局部变量 i 在 try 块中不可访问,它显示以下错误行 8

    The local variable i may not have been initialized
   

我想知道为什么会这样,是否有办法避免这种情况?

我可能已经在 try 块中包含了 catch 块下的所有代码,但我想知道在此处所示的情况下如何处理范围, 这是代码

    public static void main(String[] args) throws IOException{
    BufferedImage i;
    try {
        i=ImageIO.read(new File("forest.jpg"));
    } catch (IOException e) {
        e.printStackTrace();
    }
    panel p=new DrawImage().new panel(i);
    JFrame f = new JFrame();
    
    f.setSize(500,500);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setLocationRelativeTo(null);
    f.add(p);
    f.setVisible(true);
    
}

顺便说一下,我已经尝试了 this link 中的解决方案,但它对我不起作用。

您尚未初始化变量,i,因此出现此错误。

替换

BufferedImage i;

BufferedImage i = null;// Or any other value as per your business requirement

为什么需要这个初始化?

编译器不知道 ImageIO.read(new File("forest.jpg")) 将 return 的值是什么,因此您必须为 i 分配一些初始值,而您正在向其分配 ImageIO.read(new File("forest.jpg")).