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

Declare A Variable Using Formula Or Combination Of Variables

我想做什么

我正在尝试解析 50 个不同的站点,但我希望它一个接一个地发生,所以我将 运行 下面的代码循环。实际问题是,当我 运行 变量 linker 它应该显示 link 而不是值 A1。我不知道我说得有没有道理,这很难解释,但有没有办法让魔法发生,看起来像这样

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

我在哪里可以声明基于 formula/combination 命名的变量?

代码

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

这也行不通吗?

这里有几处错误...

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

第二:像

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

在 Java 中不起作用(它可以使用反射来完成,但对于 99% 的编程任务,你真的不需要知道这一点)...让我向你介绍一下发生:

  1. 计数器声明为值为 1 的 int
  2. Alpha 被声明为值为 "A" 的字符串(Java 约定规定变量名称以小写字母开头,但这不会影响执行)
  3. 链接器被声明为具有值 "A1"
  4. 的字符串
  5. Jsoup.connect 方法使用参数 "A1"
  6. 调用

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

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

您可以动态创建一个 String array and use an 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();
}