简体   繁体   English

Java中的变量范围-问题

[英]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: 我现在正在使用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();
}

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. 好的,所以我创建了一个名为site的Document对象,由于该人创建网站的方式,我需要添加一定数量的零,这没问题。 However when I try to use site.select(anything), I can't because the object was defined in the if construct. 但是,当我尝试使用site.select(anything)时,却不能,因为该对象是在if构造中定义的。

Also, I can not initialize it outside the if, it does not work because I get a duplicate error thrown. 此外,我无法在if之外对其进行初始化,因为我抛出了重复错误,因此无法正常工作。 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... 请告诉我有一个针对此的修复程序,因为我进行了搜索并且搜索无济于事,并且我不想将程序的其余部分放入不同的ifs中3次...

Just declare site outside the if..else blocks: 只需在if..else块之外声明site

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: 如果我对您的代码有错误并且count < 10情况缺少+ ".shtml" ,那么最佳解决方案是:

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

Move the declaration outside the if else if chain, like 将声明移到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();
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM