【发布时间】:2012-02-06 00:25:30
【问题描述】:
我需要从一个如下所示的文本文件创建一个链接列表:
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);
}
}
现在,第一个名字打印得很好,但是链接列表一直在增长,所以结果不能按我想要的方式打印......
【问题讨论】:
-
你的第二行不应该是
Leader: Fred Friends: steve Friend Count: 1吗? -
是的,刚刚改了。谢谢你接听!
标签: java linked-list