我想使用 MaxFriends 方法来查找好友最多的人。从链接列表中打印 friend 的数量很容易,但由于我在 while 循环的每次迭代后清除它,所以我不知道如何比较最后的值......
我认为如果我刚刚找到具有最多“标记”或在本例中为字符串的行,问题就可以简化。有办法做到这一点吗?
我正在读取一个文本文件(以创建链接列表)。
文本文件如下所示:
john, peter, maria, dan, george, sonja
maria, nell, ted, don, matthew, ann, john, george
fred, steve
ann, tom, maria
到目前为止的代码:
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: ");
// 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()) {
int friendCount = 0;
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());
friendCount++;
}
System.out.println("Friend Leader: " + leader + "\n" +
"\tFriends include: " + list.toString() + "\n" +
"\tNumber of Friends: " + list.size() + "\n");
} list.clear();
}
}
}
private static void error() {
System.err.println("An error has occurred: bad data");
System.exit(0);
}
public void maxFriends() {
}
}
最佳答案
如果我正确理解了这个问题,您只需跟踪到目前为止谁拥有最多的 friend ,并将其与每行的下一个候选者进行比较。将所有内容都填充到映射或堆中似乎没有必要。
顺便说一句,您所做的解析非常简单,不需要扫描仪:
String[] friends = line.split(",\\s*");
System.out.printf("%s has %d friends\n", friends[0], friends.length - 1);
关于java - 在 .txt 文件中查找数据最多的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9154598/