使用公式或变量组合声明变量

时间:2016-07-28 06:24:32

标签: java variables jsoup combinations

我正在尝试做什么

我正在尝试解析50个不同的网站,但我希望它逐个发生,所以我将在循环中运行下面的代码。实际问题在于,当我运行变量链接器时,它应该显示链接而不是值A1。我不知道我是否有意义,这是非常难以解释但是有没有办法让魔术发生可能看起来像这样

Document doc = Jsoup.connect( string (Alpha + counter)  ).get();

我可以在哪里声明基于公式/组合命名的变量?

代码

String A1 = "http://www.randomwebsite1/home.html";
String A2 = "https://sites.google.com/a/organization/contact-us";
String A3 = "http://www.alright.com/index.html";
String A4 = "http://www.youtube.com/";

public static void main(String[] args) throws IOException {

            int counter = 1;
            String Alpha = "A";
            String linker = Alpha + counter;
            Document doc = Jsoup.connect(linker).get();

3 个答案:

答案 0 :(得分:1)

您可以动态创建String array并使用enhanced for-loop进行迭代。

String[] urls = { 
        "http://www.randomwebsite1/home.html",
        "https://sites.google.com/a/organization/contact-us", 
        "http://www.alright.com/index.html",
        "http://www.youtube.com/" 
};

Document doc = null;
for (String url : urls) {
    doc = Jsoup.connect(url).get();
}

答案 1 :(得分:0)

  int n = 2  //provide the value here.It can be anything. It is the number of websites you want to loop.
  String[] A = new String[n];
    A[0] = "abc.com";
    A[1] = "xyz.com";

    for(int i=0; i<n; i++){
         Document doc = Jsoup.connect(A[i]).get();
    }

这太不起作用了吗?

答案 2 :(得分:0)

这里有些事情错了......

首先:您还没有将变量声明为静态,因此无法从静态方法(在您的情况下为main)中访问它们。

第二:这样做

int counter = 1;
String Alpha = "A";
String linker = Alpha + counter;
Document doc = Jsoup.connect(linker).get();

不能用Java工作(可以使用反射完成,但你真的不需要知道99%的编程任务)...让我带你走过什么&#39发生的事情:

  1. counter声明为值为1的int
  2. Alpha声明为值为&#34; A&#34; (Java约定规定变量名称以小写字母开头,但不会影响执行)
  3. 将链接器声明为值为&#34; A1&#34;
  4. 的String
  5. 使用参数&#34; A1&#34;
  6. 调用Jsoup.connect方法

    为了获得你想要的效果,你可以尝试将你的网址放在一个String数组中,然后遍历数组以依次获取每个网址(如Nalin Agrawal的回答所示)。

    总而言之,要么将变量声明为静态,要么在方法中声明它们,并将它们声明为字符串数组并迭代它们,而不是尝试构建要使用的变量名。