Robert Stanton
Robert Stanton

Reputation: 11

Scope of Variables in Java -- issue

Okay so I'm having a problem with scope of an object. I'm using Jsoup right now and here's the code:

//Website is /001.shtml, so adding count to the string wouldn't work. 
//This is why I have the ifs

if (count < 10)
{
 Document site = Jsoup.connect(url + "00" + count).get();
}
else if (count < 100)
{
  Document site = Jsoup.connect(url + "0" + count + ".shtml").get();
}
else
{
  Document site = Jsoup.connect(url + count + ".shtml").get();
}

Okay so I create the Document object called site, and I need to add a certain amount of zeros because of how the person made the website, no problem. However when I try to use site.select(anything), I can't because the object was defined in the if construct.

Also, I can not initialize it outside the if, it does not work because I get a duplicate error thrown. Please tell me there is a fix for this because I have searched and searched to no avail, and I don't want to have to put the rest of the program 3 times into different ifs...

Upvotes: 1

Views: 82

Answers (2)

Ted Hopp
Ted Hopp

Reputation: 234857

Just declare site outside the if..else blocks:

Document site;
if (count < 10){
    site = Jsoup.connect(url + "00" + count).get();
} else if (count < 100) {
    site = Jsoup.connect(url + "0" + count + ".shtml").get();
} else {
    site = Jsoup.connect(url + count + ".shtml").get();
}

Alternatively, you can use nested ternary operators:

Document site = Jsoup.connect(
        count < 10  ? url + "00" + count
      : count < 100 ? url + "0" + count + ".shtml"
      :               url + count + ".shtml"
    ).get();

If I'm correct that your code has a bug and the count < 10 case is missing + ".shtml", then the best solution is:

Document site = Jsoup.connect(url + String.format("%03d.shtml", count)).get();

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201527

Move the declaration outside the if else if chain, like

Document site = null;
if (count < 10) { 
  site = Jsoup.connect(url + "00" + count + ".shtml").get(); // was missing shtml.
} else if (count < 100) {
  site = Jsoup.connect(url + "0" + count + ".shtml").get();
} else {
  site = Jsoup.connect(url + count + ".shtml").get();
}

Or you might build the url and then connect once like,

String urlStr = url + String.format("%03d", count) + ".shtml";
Document site = Jsoup.connect(urlStr).get();

Upvotes: 1

Related Questions