CrimsonK9
CrimsonK9

Reputation: 31

Why am I getting a "Cannot be resolved" error in java?

I am still pretty new to Java and I'm wondering why I'm getting "Website cannot be resolved" when I'm making a ReadableByteChannel:

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);

Upvotes: 0

Views: 90

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521379

You defined Website inside the scope of the try-catch block, hence it is not visible outside that block to the rest of your method.

One quick fix would be to just declare it before the try begins, e.g.

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);

You might want to also check that website be defined before using it, or you could even move the final three lines above into a try-catch block. Note that I used website as the variable name, in line with Java coding conventions that variable names should begin with a lowercase letter.

Upvotes: 3

Related Questions