为什么我在java中出现“无法解决”错误?

问题描述:

我仍然很新的Java和我不知道为什么我得到“网站解决不了”的时候我正在做的ReadableByteChannel:为什么我在java中出现“无法解决”错误?

Date now = new Date(); 
SimpleDateFormat simpledateformat = new SimpleDateFormat("D"); 
String day = simpledateformat.format(now); 
System.out.println(day); 
String ws = "http://wallpapercave.com/wp/hMwO9WT.jpg"; 

try { 
    URL Website = new URL(ws); 
} catch (MalformedURLException e) { 
    e.printStackTrace(); 
} 
ReadableByteChannel rbc = Channels.newChannel(Website.openStream()); 
FileOutputStream fos = new FileOutputStream("weed.jpg"); 
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 
+0

因为'一旦你离开'try'块,'Website'就定义为'try'的范围,并且不会再“存在” – SomeJavaGuy

你试戴的范围内定义Website catch块,因此它在该块之外对于其余的方法是不可见的。

一个快速解决方法是在try开始之前声明它,例如,

URL website = null; 
try { 
    website = new URL(ws); 
} 
catch (MalformedURLException e) { 
    e.printStackTrace(); 
} 
ReadableByteChannel rbc = Channels.newChannel(website.openStream()); 
FileOutputStream fos = new FileOutputStream("weed.jpg"); 
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 

您可能要还检查website使用它之前定义,或者你甚至可以移动最后的三线入一个try-catch块。请注意,我使用website作为变量名称,符合Java编码约定,变量名称应以小写字母开头。

+0

当我在try块之前声明它时,它会抛出:“Duplicate local变量网站“ – CrimsonK9

+0

@ CrimsonK9这很可能是因为''网站'出现在'try'块内。不要两次_declare_网站变量,这是错误信息告诉你的。 –