我无法弄清楚为什么,我有一个由对象节点组成的二叉树,我无法发布所有代码,但它会从文件中读取约会并根据它们的最后一个插入它们名称,目前我有约5个约会,我试图添加基于姓氏的搜索功能。
它找到正确的Node,但不是返回0,而是返回-1
我的搜索方法
private boolean contains(String x, BinaryTreeNode t){
if (t == null)
return false;
int compareResult = x.compareTo(t.info.getLastName());
System.out.println("Printing t.info " + t.info.getLastName() + "\n Compare Result: " + compareResult + "\n Printing X: " + x);
if(compareResult < 0){
// System.out.println("\n Less Than \n");
return contains(x,t.left); // Its in the left subtree
}
else if (compareResult > 0){
// System.out.println("\n Greater Than \n");
return contains( x, t.right); // Its in the right subtree
}
else {
System.out.println("\n" + t.info + "\n");
return true; // Found Match
}
}
我的输出
Printing Tree
Bob, Saget, Zafar, 1/3/4, 3/5/6
Kamer, Silo, Dkido, 3/5/6, 3/5/7
Kevin, Wu, Sine, 4/5/6, 3/5/6
Mano, Billi, Zafar, 4/5/6, 3/4/5
**************************************
* XYZ Hospital Appointment Maker *
* 1. Add Appointment *
* 2. Search by Last Name *
* 3. Print Tree *
* 4. Exit *
2
Enter Last Name: Kevin
Printing t.info Bob
Compare Result: 9
Printing X: Kevin
Printing t.info Kamer
Compare Result: 4
Printing X: Kevin
Printing t.info Kevin
Compare Result: -1
Printing X: Kevin
答案 0 :(得分:2)
尽管字符串看起来很相似,但可能有尾随空格。因此,请使用trim()
方法compareTo()
。改变这个
int compareResult = x.compareTo(t.info.getLastName());
到
int compareResult = x.compareTo(t.info.getLastName().trim());
您可能还希望在致电x
compareTo