已创建img变量却提示‘img cannot be resolved’的Java问题求助
Java变量作用域问题:img无法被解析
问题代码
try { try { Image img = ImageIO.read(new File("target.png")); String imgpath = "target.png"; } catch (IOException e) { e.printStackTrace(); } } finally { int width = img.getWidth(); int height = img.getHeight(); }
错误原因
这是变量作用域导致的问题:img变量是在内部try代码块中声明的,它的作用域仅限于这个内部try块,外部的finally块无法访问到该变量,因此编译器会提示img cannot be resolved。
修正方案
方案1:提升变量作用域
将img的声明移到外部try块的外层,让finally块能够访问,同时要注意判空,避免空指针异常:
Image img = null; try { try { img = ImageIO.read(new File("target.png")); String imgpath = "target.png"; } catch (IOException e) { e.printStackTrace(); } } finally { if (img != null) { int width = img.getWidth(); int height = img.getHeight(); // 此处添加尺寸的使用逻辑 } }
方案2:在变量作用域内访问
将获取图片尺寸的代码移到内部try块中,确保在img的作用域范围内操作:
try { try { Image img = ImageIO.read(new File("target.png")); String imgpath = "target.png"; // 在img的作用域内获取尺寸 int width = img.getWidth(); int height = img.getHeight(); // 此处添加尺寸的使用逻辑 } catch (IOException e) { e.printStackTrace(); } } finally { // finally块放置不需要访问img的收尾逻辑 }
内容的提问来源于stack exchange,提问作者GR_ Gamer
相关产品推荐
相关产品推荐

