我正在从网站上检索数据,当我检索数据(字符串)时,会显示国家/地区

for (Element row : document.select("table.sortable.wikitable tr")) {

                if (row.select("td:nth-of-type(1)").text().equals("")) {
                    continue;

                }
else {
String name = row.select("td:nth-of-type(1)").text();
System.out.println(name);

}


现在,我已经确认要获取要使用列表将每个国家/地区插入到单独国家/地区对象中的国家/地区,这将为我提供控制台中的国家/地区列表。

final String url = "https://en.wikipedia.org/wiki/List_of_sovereign_states";
        List<Country> countries = new ArrayList<>();
        try {
            final Document document = Jsoup.connect(url).get();

            for (Element row : document.select("table.sortable.wikitable tr")) {

                if (row.select("td:nth-of-type(1)").text().equals("")) {
                    continue;

                } else {
                    for (Country country : countries) {

                        country.setCountry(row.select("td:nth-of-type(1)").text());


                        countries.add(country);

                    }

                }
            }
            System.out.println(countries);
        }


当我打印列表时,列表为空

[]

最佳答案

问题在这里:

else {
    for (Country country : countries) {
        country.setCountry(row.select("td:nth-of-type(1)").text());
        countries.add(country);
    }
}


考虑一下代码在做什么。按下else块时,您将在国家列表中循环浏览,然后在。 。 。创建一个新国家的次数是您列表中现有国家的次数。但是由于列表开始为空,因此该循环将永远不会执行。

解决方案很简单。完全摆脱循环,只需执行以下操作:

else {
    Country country = new Country();
    country.setCountry(row.select("td:nth-of-type(1)").text());
    countries.add(country);
}

07-24 09:49
查看更多