java - Java中过滤掉重复字符

标签 java linked-list

我正在尝试编写一个具有方法 public static void method(List<String> words) 的程序其中参数 words是文本文件 words.txt 中的单词列表已排序且仅包含每个字母仅出现一次的单词。例如,单词“feel”不会包含在此列表中,因为“e”出现多次。单词列表不会在程序的其余部分用作参数,因此方法 method仅用于存储和记住单词表以供以后使用。该函数还可以执行任何排序方法。

我的思考过程是创建一个读取文本文件的方法,并使用该文本文件作为 method 中的参数。 。 method然后会过滤掉所有出现多次的字母的单词,并对新列表进行排序。

运行程序时,我在 for (String word : words) 行上收到错误“java.util.ConcurrentModificationException: null (in java.util.LinkedList$LiSTLtr)” 。行 public static List list; 也是如此正确保存并存储list以后用吗?

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

class ABC
{
    public static List<String> list = new LinkedList<String>()
    public static List readFile()
    {
        String content = new String(); 
        File file = new File("words.txt");
        LinkedList<String> words = new LinkedList<String>();

        try
        {
            Scanner sc = new Scanner(new FileInputStream(file));
            while (sc.hasNextLine())
            {
                content = sc.nextLine();
                words.add(content);
            }
        }
        catch (FileNotFoundException fnf)
        {
           fnf.printStackTrace();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            System.out.println("\nProgram terminated safely");
        }  
        for (String word : words) 
        {
            if (letters(word) == false) 
            {
                list.add(word);
            }
        }
        Collections.sort(list);
        return list;
    }

    public static boolean letters(String word)
    {
        for (int i = 0; i < word.length() - 1; i++) 
        {
            if (word.contains(String.valueOf(word.charAt(i))) == true) 
            {
                return true;
            }
        }
        return false;
    }

    public static void main(String args[])
    {
        System.out.println(readFile());
    }

}

最佳答案

错误的根源是您正在更改正在迭代的列表。这通常不是一个好主意。

由于您正在构建一个新列表,因此实际上不需要更改正在迭代的列表。我建议更改您的代码,以便决定一个字母是否多次出现的逻辑放入单独的方法中。这样,任何给定方法的复杂性都是可控的,并且您可以单独测试它们。

因此,创建一个新方法来测试是否有字母出现多次:

static boolean doesAnyLetterAppearMoreThanOnce(String word) {
    ...
}

然后您可以在现有方法中使用它:

    for (String word : words) {
        if (!doesAnyLetterAppearMoreThanOnce(word)) {
            list.add(word);
        }
    }
    Collections.sort(list);

关于java - Java中过滤掉重复字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60996030/

相关文章:

java - CXF + Java : How to remove xmlns attribute

go - 如何在链表的给定索引处插入节点

java - 用户 'user' @'localhost' 的 MySQL 访问被拒绝(使用密码 : yes) "openshift"

java - 作为参数传递的编辑列表似乎不起作用

java - jackson 与 builder 模式

java - LinkedList 上的 removeFirst() remove(0) 之间的区别?

java - 在 Java 中使用带有链表的迭代器

java - 如何在java中使用JSlider放大和缩小行中的图像?

c - 在C中按计数属性对链表结构进行排序(在Ubuntu中通过文本文件读入)

c - 队列.h : how to create list of lists/queue of queues/similar combinations?