如何检查成员是否存在

时间:2014-03-11 09:50:39

标签: java

所以我已经实现了insert方法,它工作正常,但我的问题是如何检查成员是否已经在列表中,我希望程序检查该成员是否已经在列表中但是检查器不起作用。我希望程序将成员放在team1中,如果该成员包含在列表中,并且如果该成员不在列表中,则显示“成员不存在”。我做了一个检查方法,但它不起作用。我是编程新手,我真的需要帮助。请用你的知识启发我。

class Node
{
    protected String info;
    protected Node next;
    public Node(String value)
    {
        info = value;
        next = null;
    }
}
class LinkedList
{
    private Node head;
    private int count;
    public LinkedList()
    {
        head = null;
        count = 0;
    }
    public void insert( String name)
    {
        Node a = new Node(name);
        a.next = null;
        count++;
        if (head == null)
        {
            head = a;
            return;
        }
        for(Node cur = head; cur != null; cur = cur.next)
        {
            if (cur.next == null)
            {
                cur.next = a;
                return;
            }
        }
    }

    public void checker(String name)
    {

        for(Node cur = head; cur != null; cur = cur.next)
        {
            if(cur.info == name)
            {
                insertteam1(name);
                System.out.print("OK");
            }
            else
            {
                System.out.print("member does not exist");
            }
        }
    }
    public void insertteam1(String name)
    {
        Node b = new Node(name);
        b.next = null;
        count++;
        if (head == null)
        {
            head = b;
            return;
        }
        for(Node cur = head; cur != null; cur = cur.next)
        {
            if (cur.next == null)
            {
                cur.next = b;
                return;
            }

        }
    }

1 个答案:

答案 0 :(得分:2)

在下面的代码中,

if(cur.info == name){ // }

您正在使用==比较字符串信息,这不是比较java中字符串的正确方法。

使用 if(cur.info.equals(name)){ // }

如果您想进行不区分大小写的比较,请使用if(cur.info.equalsIgnoreCase(name)){ // }