java - 搜索链接列表以进行匹配

标签 java

我试图在链接列表中搜索匹配项,但总是出错。这是我的代码:

列表已填写,文件为

 try
        {
            BufferedReader infile =
                new BufferedReader(new FileReader("C:\\videoDat.txt")); .....

       public static void createVideoList(BufferedReader infile,
                                       VideoList videoList)
                                       throws IOException
    {
        String  title;
        String  star1;
        String  star2;
        String  producer;
        String  director;
        String  productionCo;
        int   InStock;



        title = infile.readLine();
 //If the title exists then there is the rest
        while ((title=infile.readLine()) != null)   {
            // Fill Linked list
          star1=infile.readLine();
          star2=infile.readLine();
          producer=infile.readLine();
          director=infile.readLine();
          productionCo=infile.readLine();
          InStock=infile.read();
          VideoElement MovieObject=new VideoElement();
          MovieObject.setVideoInfo(title,star1,star2,producer,
          director,productionCo,InStock);
            videoList.addToList(MovieObject);
            title=infile.readLine();
        }//end while
    }//end createVideoList

使用 equals 方法搜索:

public boolean searchVideoList(String title)
{

    for(VideoElement x:VideoList)
    {
        if(x.equals(title))
        {
            return true;
        }

    }
        return false;


}//end searchVideoList 

从主方法调用搜索:

System.out.print("Enter the title: ");
                        title = in.readLine();
                        System.out.println();
                        if(videoList.searchVideoList(title)==true)
                            System.out.println("Title found.");
                        else
                            System.out.println("Video not in store.");
                        break;

抱歉,我什至没有意识到它正在使用老师为我们提供的 VideoElement 中覆盖的 equals 方法:

  public boolean equals(DataElement otherElement)
    {
        VideoElement temp = (VideoElement) otherElement;
        return (videoTitle.compareTo(temp.videoTitle) == 0);
    }

我总是收到不在商店中的视频,因为 searchvideolist 最后总是返回 false。但如果我删除它,它会告诉我我需要返回一些东西..该怎么办..

最佳答案

  1. VideoElement 是否以任何方式扩展 String?
  2. VideoElement 中的 equals() 方法是如何实现的? -> 你应该知道 equals 用于比较相同类型的对象,所以除非 VideoElement 和 String 相同否则你会得到 false。

尝试将您的方法更改为: for(VideoElement x:VideoList) { if(x.getTitle().equals(标题)) { ... }

关于java - 搜索链接列表以进行匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9256017/

相关文章:

java - 多客户端广播中的 MulticastSocket 与 DatagramSocket

java - 添加到 HashSet 时出现空指针异常

java - 部署到tomcat中的网络套接字编程显示错误

Java-8:流还是更简单的解决方案?

java - Derby 数据库 : how to find string in Blob field

java - 如何 jsonify 具有新值的对象?

java - 在 Maven 构建中跳过运行 PITest

java - JDK 1.8 on unicode escape characters gives string literal is not properly closed by a double-quote 错误

java - 实现动画后 ImageButton 不可点击

java - Netty 中是否有类似 transferFrom 的零拷贝功能?