【问题标题】:Finding a word in file storing it in an array list and making sure that word isn't accounted for more than once?在文件中查找一个单词并将其存储在一个数组列表中并确保该单词不被多次占用?
【发布时间】:2017-07-01 00:06:28
【问题描述】:
public ArrayList<String> getWords()
{
    int size1 = lines.size();
    int size2 = 0;
    int counter3 = 0;
    ArrayList<Integer> checkthewords;
    for (int x = 0; x < size1; x++)
    {
        size2 = lines.get(x).substring(x).length();
        for (int y = 0; y < size2; y++)
        {
            if (Character.isLetter(charAt(((lines.get(x)).indexOf(x, z + x)))))
            {
                words.set(z, lines.get(x).substring(x,z + 1));
            }
            else
            {
                checkthewords.set(counter3, words);
                counter3++;
            }
            if (checkthewords.get(x).equals(checkthewords.get(counter3)))
            {

            }
        }
    }
    return words;
}

上面的方法是一个叫做getWords()的方法。我正在尝试从文件中获取一个单词并将其存储在 arrayList checkthewords 中。我想确保一个单词不会多次存储在 arrayList checkthewords 中。

我有 if 语句:

            if (Character.isLetter(charAt(((lines.get(x)).indexOf(x, z + x)))))

但是,不知道从那里去哪里。

【问题讨论】:

  • 你能用集合代替列表吗?
  • getWords() 应该返回什么?一个独特的单词列表? LinkedHashSet 可能是解决这个问题的方法(假设您需要保留插入顺序)。
  • 你的意思是普通数组吗?
  • getWords() 应该返回一个包含文件所有单词的数组或数组列表
  • 如果这是家庭作业,我认为使用LinkedHashSet 可能不是理想的解决方案,而是需要手动处理重复项。 @J。如果您为变量使用有意义的名称,您是否可以使您的代码更清晰:size1size2counter3xy - 这些都传达了关于其用途的零信息。

标签: java


【解决方案1】:

我很确定您的代码目前不会运行。你在那里做了一些奇怪的事情,我真的不明白。

尝试一步一步来。

第一步是从文件中获取单词。确保您可以解析line 并提取您想要的单词。

然后你需要检查这个词是否存在于你的checkthewords 列表中。如果它不存在,请添加它。您可以使用List 提供的contains 方法来查看列表是否包含内容。

if(!checkthewords.contains(word)) {
    // it's not in the list yet, add it
    checkthewords.add(word);
}

此外,当您创建 checkthewords 列表时,您不会对其进行初始化(因此它为空):

ArrayList<String> checkthewords;

应该是:

ArrayList<String> checkthewords = new ArrayList<String>();

而且你不应该那样使用checkthewords.set()set 用于替换现有元素,而不是添加新元素。您可以轻松设置一个尚不存在的元素并抛出ArrayIndexOutOfBoundsException。使用 checkthewords.add(word) 向您的列表添加内容。

请参阅ArrayList documentation

set(int index, E element)

将此列表中指定位置的元素替换为指定元素。

看来你想多了。把事情简单化。 :)

【讨论】:

  • 非常感谢马特,这更有意义。
【解决方案2】:

当不允许重复时,您应该在 Java 中使用 Set 来存储元素。

一个不包含重复元素的集合。

如果您还想保留插入顺序,请使用LinkedHashSet 这是 Set 接口的哈希表和链表实现,具有可预测的迭代顺序。

请参考以下教程了解Set在java中的应用。
Tutorial 1
Tutorial 2
Tutorial 3

另见-:
HashSet vs TreeSet vs LinkedHashSet
HashSet vs LinkedHashSet

【讨论】:

    猜你喜欢
    • 2016-07-08
    • 2016-08-19
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 2020-06-27
    相关资源
    最近更新 更多