0

以下用Java编写的代码

public static void main (String [] args) throws Exception
{
    ordListe ol = new ordListe();
    ol.lesBok("navn.text");
    ol.leggTilOrd("hello");
    ol.leggTilOrd("Hello");

是我的主要方法。这是关于从文件中读取并添加到数组列表(字典)。''Hello'' 和 "hello" 应该是同一个词,并且在下面的代码中,它应该增加那个词的计数。

for (int i = 0; i < ordListe.size(); i++)
    {
        if (ordListe.toString().contains(s))
        {
            if (ordListe.get(i).toString().equalsIgnoreCase(s))
            {
                ord.oekAntall();
                System.out.println("'" + s + "' That word is found and there are " + ord.hentAntall() + " of that word now in dictionary.");
                break;
            }
        }

        else
        {
            Ord ny = new Ord(s);
            ordListe.add(ny);
            System.out.println("'" + s + "' This word is added. " + ny.hentAntall() + " of this word in dictionary.");
            break;
        }
    }

所以这是我的代码的一部分。从主要方法中,我添加了类似ol.leggTilOrd("hello"); leggTilOrd我的方法的词,上面的代码是从中获取的。这是将单词添加到字典/arrayList 并检查 inputwords 是否已经存在的代码部分。if (ordListe.get(i).toString().equalsIgnoreCase(s))除了特定的部分,我对其他任何事情都没有问题。如果 arrayList 中存在一个单词,我应该增加该单词的计数。如果没有,我在数组列表(ordListe)中添加单词。问题是,即使我添加ol.leggTilOrd("hello")or ol.leggTilOrd("Hello"); 大写的“H”,即使我使用上面的陈述,我也无法将它识别为同一个词。我该怎么做,还有其他可能吗?这是我之前的多次尝试之后的最后一次尝试。

如果上面有任何疑问,请告诉我。

4

2 回答 2

0

在比较之前将两个字符串都更改为小写,然后comapare ..它将帮助您并且更容易!!!使用 toLower 函数,然后比较

于 2014-10-19T18:02:51.933 回答
0

问题是这一行:

if (ordListe.toString().contains(s))

因为 1)您不比较两个字符串的小写或大写版本,并且 2)您可能没有覆盖 toString,因此它会按照您的预期返回列表中的项目。假设您的 ordliste 扩展了 arraylist,则将此函数放在您的 ordListe 类中:

public boolean containsIgnoreCase(String item) {
     for(int i = 0; i < size(); i++) {
           if (get(i).toString().equalsIgnoreCase(item)) {
               return true;
           }
     }

     return false;
}

现在您可以调用 containsIgnoreCase 来确定列表中是否存在忽略大小写的特定项目

于 2014-10-19T18:29:43.243 回答