1

我有一个程序,它使用 Jsoup 获取特定球队的曲棍球运动员的统计数据并将其放入单个字符串中。我想将线路分开,以便我可以在他们自己的字符串中获取每个玩家的统计数据。这是我拥有并解释的代码:

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


    Document doc = Jsoup.connect("http://espn.go.com/nhl/team/stats/_/name/phi/philadelphia-flyers").get();

    for (Element table : doc.select("table.tablehead")) {
        for (Element row : table.select("tr")) {
            Elements tds = row.select("td");
             if (tds.size() > 6) {
                String a = tds.get(0).text() + ":" + tds.get(1).text() + " GOALS: " + tds.get(2).text() + " ASSISTS: " + tds.get(3).text() + " POINTS: " + tds.get(4).text() + " PLUS/MINUS: " + tds.get(5).text() + " PIM: " + tds.get(6).text();
                System.out.println(a);
            }
        }
    }
}

输出给出了多行,为了让您了解这些是它给出的前三行:

PLAYER:GP GOALS: G ASSISTS: A POINTS: PTS PLUS/MINUS: +/- PIM: PIM
Matt Read, C:13 GOALS: 5 ASSISTS: 4 POINTS: 9 PLUS/MINUS: 2 PIM: 2
Brayden Schenn, C:12 GOALS: 2 ASSISTS: 6 POINTS: 8 PLUS/MINUS: 3 PIM: 5

如果行的开头 = Matt Read 我想创建一个包含以下内容的字符串:

Matt Read, C:13 GOALS: 5 ASSISTS: 4 POINTS: 9 PLUS/MINUS: 2 PIM: 2

如果行的开头 = Brayden Schenn 我想创建一个包含以下内容的字符串:

Brayden Schenn, C:12 GOALS: 2 ASSISTS: 6 POINTS: 8 PLUS/MINUS: 3 PIM: 5
4

3 回答 3

3

除非我不理解代码,否则您似乎几乎已经这样做了 - 每一行都String a在每次循环迭代的变量中。您只需要向外保存a. ArrayList<String>在您的初始 for 循环之前实例化 a并a在您调用System.out.println(a);. 退出 for 循环后,您ArrayList应该包含每个适当的个人String.

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

    List<String> list = new ArrayList<String>(); // THIS LINE IS NEW

    Document doc = Jsoup.connect("http://espn.go.com/nhl/team/stats/_/name/phi/philadelphia-flyers").get();

    for (Element table : doc.select("table.tablehead")) {
        for (Element row : table.select("tr")) {
            Elements tds = row.select("td");
             if (tds.size() > 6) {
                String a = tds.get(0).text() + ":" + tds.get(1).text() + " GOALS: " + tds.get(2).text() + " ASSISTS: " + tds.get(3).text() + " POINTS: " + tds.get(4).text() + " PLUS/MINUS: " + tds.get(5).text() + " PIM: " + tds.get(6).text();

                    list.add(a);  // THIS LINE IS NEW

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

        // at this point, variable "list" contains each String assigned to "a" above.

}
于 2013-02-12T22:33:13.133 回答
1

您可以使用 Scanner 类通过调用scanner.nextLine() 方法从任何文本主体(或直接从文件)中提取单独的行。它只会扫描输入字符串,直到遇到换行符,然后将所有内容返回给它。

于 2013-02-12T22:35:35.403 回答
1

您可以使用扫描仪,或者更适合使用 List,甚至是 HashMap 来存储有关玩家的信息。

不要打印该行,而是声明您喜欢的类型并将字符串 a 存储在那里。

于 2013-02-12T22:52:22.490 回答