文本文件中的链接列表(打印故障)

时间:2012-02-06 00:25:30

标签: java linked-list

我需要从文本文件中创建一个链接列表,如下所示:

john, peter, maria, dan, george, sonja
fred, steve
ann, tom, maria
//etc...

我想打印每一行(领导者)中的第一个名称以及该行中的其余名称(与该名称相关联)。

例如:

Leader: John Friends: peter, maria, dan, george, sonja Friend Count: 5
Leader: Fred Friends: steve Friend Count: 1
//etc...

这是我到目前为止所做的:

import java.util.*;
import java.io.*;

import javax.swing.JFileChooser;
public class Test {

public static void main(String[] args) {
    LinkedList<String> list = new LinkedList<String>();

    LinkData ld1 = new LinkData();
    JFileChooser chooser = new JFileChooser(".");
    int returnVal = chooser.showOpenDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        System.out.println("You chose to open this file: "
                + chooser.getSelectedFile().getName()
                + "Print some info"

        // open and read file:
        Scanner scanner = null;
        try {
            scanner = new Scanner(chooser.getSelectedFile());
        } catch (IOException e) {
            System.err.println(e);
            error();
        } 

        if (scanner == null)
            error();


        while (scanner.hasNextLine()) {

            String line = scanner.nextLine();
            Scanner lineScan = new Scanner(line);
            lineScan.useDelimiter(", ");
            // System.err.println("The line that was scanned: " + line);

            String leader = lineScan.next();

            while (lineScan.hasNext()) {
                list.add(lineScan.next());
            }
            System.out.println("Leaders include_" + leader + list.toString());
        }  
    }
        }

private static void error() {
    System.err.println("An error has occurred: bad data");
    System.exit(0);
}
}

现在,第一个名称打印正常,但随后链表不断增长和增长,因此结果不会按照我想要的方式打印...

2 个答案:

答案 0 :(得分:1)

你应该clear()两行读取之间的列表

while (scanner.hasNextLine()) {
  list.clear();
  //...
}

答案 1 :(得分:0)

你走在正确的轨道上。您正在将每一行处理为leaderfriends列表。您将需要跟踪另一个对象中的每个实体 - 我会推荐一个Map。类似的东西:

Map<String, List<String>> leaderMap = new HashMap<String, List<String>>();

// ...
String leader = lineScan.next();

while (lineScan.hasNext()) {
    list.add(lineScan.next());
}

leaderMap.put(leader, list);

不要忘记重新初始化从文件中读取的每一行的列表。最后,您可以迭代地图,打印密钥(leader)和关联列表的大小(number of friends)。祝你好运!