我正在尝试编写一个具有方法 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/