简体   繁体   English

Java将未知项目添加到arraylist

[英]Java adding unknow item to arraylist

hi I have a quick question. 嗨,我有一个快速的问题。

I'm having a problem with adding an item from an input.txt file to a new list. 我在将input.txt文件中的项目添加到新列表时遇到问题。

I have a file with 28 items, with names and numbers, 27 of them are part of the categories and lists I've created. 我有一个包含28个项目的文件,其中包含名称和数字,其中27个是我创建的类别和列表的一部分。 But then there is another one that should be treated and included in a new category called "unknown items", this one should include any item that is there or might be added not belonging to those lists, including misspells. 但是,还有另一项应该处理,并包含在称为“未知项目”的新类别中,该项目应包括存在或可能添加的不属于那些列表的任何项目,包括拼写错误。

Anyway, I created ArrayLists for my categories and for my lists. 无论如何,我为我的类别和列表创建了ArrayLists。 This my code for those and it works fine: 这是我的代码,可以正常工作:

for(Items i : list) {
        for(String name: cat1) {
            if(i.name.equalsIgnoreCase(name))
                lista1.add(i);
        }

but then when I try to to make the same for the unknown items list, it doesn't work, right now what I get is the exact opposite of what I need and it's the closest I've been from sorting it out, it's including 27 items and excluding the one I need and when I try to invert it, it just gets screwed up and I just can't figure out what I'm doing wrong, this is what I have: 但是,当我尝试对未知物品列表进行相同处理时,它不起作用,现在我得到的与我所需要的完全相反,这是我从排序中得到的最接近的结果,包括27个项目,不包括我需要的项目,当我尝试对其进行反转时,它只会被弄乱,而我只是无法弄清楚自己在做错什么,这就是我所拥有的:

next:
        for(String name: catAll){
            if(!i.name.equalsIgnoreCase(name)) continue next;

                listUnknow.add(i);
        }

If anyone could help me out I'd appreciate it. 如果有人可以帮助我,我将不胜感激。

Thanks 谢谢

You're looking for something like this: 您正在寻找这样的东西:

for(Items i : list) {
    boolean unknown = true;
    for(String name: cat1) {
        if(i.name.equalsIgnoreCase(name)) {
            lista1.add(i);
            unknown = false;
            break;
        }
    }
    if(unknown) {
        listUnknown.add(i);
    }
}

The problem with your code is that inverting doesn't work like you think it does. 代码的问题在于,反相无法像您想象的那样工作。 If your cat1 contains "a", "b" and your current item is a "b", then the first check will return true. 如果您的cat1包含“ a”,“ b”,而您的当前项目是“ b”,则第一个检查将返回true。 After all, !"b".equalsIgnoreCase("a") is true. 毕竟, !"b".equalsIgnoreCase("a")为true。 You need to check all items in cat1 before you can say it is unknown. 您需要先检查cat1中的所有项目,然后才能说它未知。

Don't know what p & i is in your second snippet but it starts the loop on every continue... maybe try without the label (to skip adding)? 不知道第二个片段中的p&i是什么,但是每次继续时它都会开始循环...也许尝试不使用标签(跳过添加)?

for(String name: catAll){
        if(!i.name.equalsIgnoreCase(name)){
          continue;
        }

        listUnknow.add(p);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM