java - 在 .txt 文件中查找数据最多的行

标签 java text-files

我想使用 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/

相关文章:

java - Android:在另一个 Activity (由该 RecyclerView 启动)调用 finish() 后,RecyclerView 项目的 onClick() 被无意激活

java - 如何确定文件是否被附加或彻底更改

java - 在Java中将资源文本文件读取为字符串

java - 检查 URL 是否存在(方法不适用于 "http://"字符串)

java - 如何使用 libgdx 中的简单纹理绘制自定义形状?

java - 在Java中逐行读取和替换特定单词的问题

php - SplFileObject 将指针移动到上一行

matlab - 在Matlab中读取txt文件

java - 如何将 LocalDate 转换为 SQL Date Java?

java - MongoDB 中的 db.eval() 错误