我正在尝试搜索链接列表中的匹配但总是变得虚假。这是我的代码:
列表填充infile是
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
从main方法调用搜索:
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中的overided equals方法:
public boolean equals(DataElement otherElement)
{
VideoElement temp = (VideoElement) otherElement;
return (videoTitle.compareTo(temp.videoTitle) == 0);
}
我总是把视频放在商店里,因为searchvideolist总是在结尾处返回false。但如果我删除它,它告诉我,我需要返回一些东西..做什么..
答案 0 :(得分:1)
尝试将您的方法更改为: for(VideoElement x:VideoList) { 如果(x.getTitle()。等于(标题)) { ... }
答案 1 :(得分:0)
您的文件C:\videoDat.txt
是否包含由换行符('\ n'),回车符('\ r')或者任意一个终止的输入(title,star1,star2,producer等)回车后立即换行。
请在使用BufferedReader.readLine()
时确保这一点,因为它会读取一行文字。
此外,在您的以下代码中:
for(VideoElement x:VideoList)
{
if(x.equals(title))
{
return true;
}
.....
您正在将VideoElement
对象x
与String
title
进行比较。你试过纠正吗?
答案 2 :(得分:0)
我最终像这样修理它:
boolean videoSearch(String title){
VideoElement temp = new VideoElement();
boolean found = false;
for(ListIterator<VideoElement> Vitr = VideoList.listIterator();Vitr.hasNext();){
temp=Vitr.next();
if(temp.checkTitle(title)){
//item is found
found = true;
break;
}
else
found=false;
}
return found;
}