gpt4 book ai didi

java - 从文件中读取 ArrayList。打印只出现一次的单词

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:49:15 25 4
gpt4 key购买 nike

编码和 Java 的新手,请善待 :)

我正在为学校做一个项目,我正在尝试迭代从文本文件中读入的 ArrayList

我使用扫描仪将文件读取到 ArrayList 中,然后使用 Collections.sort()ArrayList 进行排序,希望我可以用下一个元素检查每个元素。如果该元素与下一个元素相同,则忽略并继续,但如果该元素在 ArrayList 中没有重复,则将其添加到新的 ArrayList.

因此,当读取包含这些词的文本文件时:

this this is a a sentence sentence that does not not make sense a sentence not sentence not really really why not this a sentence not sentence a this really why

新的ArrayList应该是

是否有意义

因为这些词只出现一次。

public static void main (String[] args) throws FileNotFoundException {   
Scanner fileIn = new Scanner(new File("words.txt"));
ArrayList<String> uniqueArrList = new ArrayList<String>();
ArrayList<String> tempArrList = new ArrayList<String>();

while (fileIn.hasNext()) {
tempArrList.add(fileIn.next());
Collections.sort(tempArrList);
}

for (String s : tempArrList) {
if(!uniqueArrList.contains(s))
uniqueArrList.add(s);

else if (uniqueArrList.contains(s))
uniqueArrList.remove(s);

Collections.sort(uniqueArrList);
System.out.println(uniqueArrList);
}

这是我目前所拥有的,但我一直以这个 [a, does, is, make, really, sense, that]

我希望有人能告诉我我做错了什么:)

最佳答案

您的算法不正确,因为它一直在 uniqueArrList 中添加和删除项目。因此,它会找到出现奇数次的单词,并且它不关心要排序的列表。

您可以对列表进行一次排序(将 sort 移出循环),然后使用一个非常简单的策略:

  • 使用整数索引遍历列表
  • 将当前索引处的单词与下一个索引处的单词进行比较
  • 如果单词不同,则打印当前单词,索引加一
  • 如果单词相同,则向前遍历列表直到看到不同的单词,然后使用该单词的位置作为循环索引的下一个值。

这是一个示例实现:

Scanner fileIn = new Scanner(new File("words.txt"));
List<String> list = new ArrayList<>();
while (fileIn.hasNext()) {
list.add(fileIn.next());
}
Collections.sort(list);
int pos = 0;
while (pos != list.size()) {
int next = pos+1;
while (next != list.size() && list.get(pos).equals(list.get(next))) {
next++;
}
if (next == pos+1) {
System.out.println(list.get(pos));
}
pos = next;
}

Demo.

关于java - 从文件中读取 ArrayList。打印只出现一次的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46721393/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com