我试图在链表中查找匹配项,但总是会出错。这是我的代码:

列表填充文件为

 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。但是,如果我删除它,它告诉我我需要退货。该怎么办..

最佳答案

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


尝试将您的方法更改为类似以下内容:
对于(VideoElement x:VideoList)
{
if(x.getTitle()。equals(title))
{
...
}

08-06 17:00