【问题标题】:How to search int key from doubly linkedlist?如何从双向链表中搜索 int 键?
【发布时间】:2015-07-13 07:31:00
【问题描述】:

关键是用户的输入。 我正在尝试将 int 键与字符串 id 进行比较,以查看它们是否相等。 如果字符串 id == int 键。然后只需返回此链接。 否则,我想比较列表中的所有 id。

1. Add a student to records
2. Remove a student from records
3. Search a student from records
4. Display all students in records
5. Quit

当我输入 3 个学生时,它只比较第一个和最后一个。 我该如何解决?谢谢你的帮助:)

public Link searchStudent(int key)
{ 
    Link temp = new Link(null,null);
    temp = cursor;
    int idNumber=0;

    if(size>=key){
        System.out.println("Ready to Search...");       
        for(int i = 0; i < size; i++){

            System.out.println("key--->"+key);
            System.out.println("id--->"+temp.getId());

            idNumber = Integer.parseInt(temp.getId());
            if(idNumber==key)
                System.out.println("You found it!");
            else
                temp = cursor.next;
        }

    }
    return temp;        
}

【问题讨论】:

  • 您需要提供更多代码。您的 searchStudent 方法中有对明显在此方法之外初始化的字段的引用。

标签: java doubly-linked-list


【解决方案1】:

问题是您没有在循环内更改tempcursor 变量。我只能猜测cursor 在您的班级中的含义,但是如果您将其视为列表的首位,那么您需要在每次迭代时更改temp。此外,当您找到 id 等于 key 的元素时,我猜您想停止搜索。请参阅下面的代码。

public Link searchStudent(int key) { 
    Link temp = cursor;
    int idNumber = 0;

    if(size >= key) {
        System.out.println("Ready to Search...");       
        for(int i = 0; i < size; i++) {

            System.out.println("key -> " + key);
            System.out.println(" id -> " + temp.getId());

            idNumber = Integer.parseInt(temp.getId());
            if(idNumber == key) {
                System.out.println("You found it!");
                break;
            } else {
                // Here!
                temp = temp.next;
            }
        }

    }
    return temp;        
}

【讨论】:

    【解决方案2】:

    您可以尝试将 String 与 int 匹配

            if(temp.getId().equals(key+""))
                System.out.println("You found it!");
    

    或者这个

      String sKey=key+"";   
      if(skey.equals(temp.getId())
           System.out.println("You found it!");
    

    【讨论】:

      猜你喜欢
      • 2012-03-22
      • 1970-01-01
      • 1970-01-01
      • 2011-04-14
      • 1970-01-01
      • 1970-01-01
      • 2012-07-15
      • 1970-01-01
      • 2019-06-23
      相关资源
      最近更新 更多