Java中变量的作用域——问题

Java中变量的作用域——问题,java,Java,好的,我对一个对象的范围有问题。我现在正在使用Jsoup,下面是代码: //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) { Doc

好的,我对一个对象的范围有问题。我现在正在使用Jsoup,下面是代码:

//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();
}
//网站是/001.shtml,因此向字符串中添加count将不起作用。
//这就是为什么我有国际单项体育联合会
如果(计数<10)
{
documentsite=Jsoup.connect(url+“00”+count).get();
}
否则,如果(计数<100)
{
documentsite=Jsoup.connect(url+“0”+count+“.shtml”).get();
}
其他的
{
documentsite=Jsoup.connect(url+count+“.shtml”).get();
}
好的,我创建了一个名为 网站,我需要添加一定数量的零,因为这个人是如何创建网站的,没有问题。但是,当我尝试使用site.select(任何内容)时,我都不能,因为该对象是在if构造中定义的


另外,我不能在if之外初始化它,因为我抛出了一个重复的错误,所以它不工作。请告诉我有一个解决方案,因为我已经搜索了又搜索,但没有结果,我不想将程序的其余部分放入不同的ifs中3次…

只需在
if..else
块之外声明
站点

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

将声明移到
if
else if链之外,如

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

我已经试过了,不幸的是它不起作用,我也不知道为什么。我已经试过了,但由于站点重复,它不起作用。@RobertStanton-什么站点重复?请注意,在我的代码中,当在
if
块中使用
site
时,我已经删除了类型名。声明中不赋值
null
时使用+1,因此如果您在使用它之前忘记正确初始化,编译器将警告您。您应该使用字符串格式化程序。这样将使输入为3位数字:String.format(“%03d”,numberValueHere)您所说的“它不工作”是什么意思?请提供一条错误消息,并包括一个触发错误的最小程序。
Document site = Jsoup.connect(url + String.format("%03d.shtml", count)).get();
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();
}
String urlStr = url + String.format("%03d", count) + ".shtml";
Document site = Jsoup.connect(urlStr).get();