compareTo returns -1 even though strings match Java -
i can't figure out why, have binary tree made of object nodes, can't post code reads appointments file , inserts them based on lastly name, have 5 appointments, trying add together search functionality based on lastly name.
it finds right node, instead of returning 0, returns -1
my search method
private boolean contains(string x, binarytreenode t){ if (t == null) homecoming 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 \n"); homecoming contains(x,t.left); // in left subtree } else if (compareresult > 0){ // system.out.println("\n greater \n"); homecoming contains( x, t.right); // in right subtree } else { system.out.println("\n" + t.info + "\n"); homecoming true; // found match } }
my output
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 together appointment * * 2. search lastly name * * 3. print tree * * 4. exit * 2 come in lastly 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
although strings similar there maybe trailing spaces. utilize trim()
compareto()
method. alter
int compareresult = x.compareto(t.info.getlastname());
to
int compareresult = x.compareto(t.info.getlastname().trim());
you may trim x
before calling compareto
java string search binary-search-tree compareto
No comments:
Post a Comment