有一个LinkedQueueClass
有3个要素:如何用字符串值搜索LinkedQueueClass
"ABC"
"XYZ"
"123"
的元素中的LinkedListQueue
是定制类类型StringElement
其中有一个数据成员,它拥有一个字符串(字数据会员)。
StringElement
: http://pastebin.com/zh0t2X5K
当我尝试使用search()
功能来搜索,实际上在队列中的boolean
值返回是false
存在的元素。意味着它无法找到元素。
Main
: http://pastebin.com/vGegkcLZ
我在哪里出了错?
EDIT(代码从Pastebin.org链接如上所述。)
主要:
public class StringElement extends DataElement {
protected String word;
public StringElement(String str)
{
word = str;
}
public StringElement(StringElement otherElement)
{
word = otherElement.word;
}
@Override
public boolean equals(DataElement otherElement) {
StringElement temp = (StringElement) otherElement;
return (word == temp.word);
}
@Override
public int compareTo(DataElement otherElement) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void makeCopy(DataElement otherElement) {
StringElement temp = (StringElement) otherElement;
word = temp.word;
}
@Override
public DataElement getCopy() {
StringElement temp = new StringElement(word);
return temp;
}
@Override
public String toString()
{
return String.valueOf(word);
}
}
StringElement:
import java.util.Scanner;
public class Run {
public static void main(String args[]){
LinkedQueueClass strQueue = new LinkedQueueClass();
strQueue.addQueue(new StringElement("ABC"));
strQueue.addQueue(new StringElement("XYZ"));
strQueue.addQueue(new StringElement("123"));
System.out.println();
//ask user for a keyword to search for
System.out.print("Search keyword: ");
Scanner scan = new Scanner(System.in);
String userInput;
userInput = scan.next();
//place the entered keyword into a StringElement and use it
//to search for the element with mathing keyword
StringElement keyword = new StringElement(userInput);
System.out.println(keyword.toString());//debugging: to confirm userInput value got stored in keyword object
System.out.println(strQueue.search(keyword));//search returns false
}
}
搜索()从UnorderedLinkedList:
public boolean search(DataElement searchItem)
{
Node current; //pointer to traverse the list
boolean found;
current = first; //set current pointing to the first
//node in the list
found = false; //set found to false
while(current != null && !found) //search the list
if(current.info.equals(searchItem)) //item is found
found = true;
else
current = current.link; //make current point to
//the next node
return found;
}
您构建的关键字对象是从搜索对象不同。您正尝试搜索不同的对象,但内容相同。 – r0ast3d