Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 2 12 LastLast
Results 1 to 25 of 29

Thread: Sorted list and compareTo method

  1. #1
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Sorted list and compareTo method

    Hey, so I need to write a program that simulates a phonebook. The program should contain the options to lookup a person,delete a person,insert a person, and too check the size(amount of persons inside the phonebook) now we're given a class Person, and an interface Phonebook. We're susposed to implement the interface in our class and use the methods insert,delete,lookup in order to do these tasks. This is what I've got so far;

     
    class PhoneBookList implements PhoneBook {
    	private int size = 0;
    	Node head = null;
     
    	Person lookup(String name) {
    		Node p = head;
    		int pos = 0;
     
    		while( p!=null) {
    			int comparison = p.compareTo(name);
     
    		if(comparison == 0) 
    			return name;
    		else Out.println("Person does not exist");
    		    return -1;
    		}
    	}
     
    	boolean insert(Person person) {
    		Node p = head;
    		Node prev = null;
     
    		while( p!=null) {
     
    		Node n = new Node(person);
    		n.next = p;
     
    		if(prev == null) {
    			head = n;
    		}else{
    			prev.next = n;
    	}
    		size++;
    }
     
    	boolean delete(String name) {
    		Node p = head;
    		Node prev = null;
     
    		while( p!=null) {
    			prev = p;
    			p = p.next;
    			int comparison = p.compareTo(name);
     
    		if(comparison == 0) {
    			prev.next = p.next;
    			return true;
    		}else {
    			Out.println("The person does not exist");
    			return false;
    		}
    		size--;
    	}
    }	
    	int size() {
    		Out.println(size);
    	}
     
    	static final class Node {
    		final Person person;
    		Node next;
     
    		Node(Person person) {
    			this.person = person;
     
    		}
    	}
     
    }
    }

    Now I'm not sure if I am doing this right, we are also suspossed to use this compareTo method to check if the person does exist,if yes ok if not give out an error.The same analogy applies for the methods delete and insert. Am I using these methods right and if not what am I doing wrong? Thanks!

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Sorted list and compareTo method

    Am I using these methods right
    Do they do what you want them to do? Do you get the correct result?

    A suggestion: write a simple short program that calls the compareTo method 3 times:
       System.out.println("smaller " + var1.compareTo(var0));
       System.out.println("equal " + var2.compareTo(var0));
       System.out.println("bigger " + var3.compareTo(var0));
    Use var1 < var0, var2 == var0 and var3 > var0

    Run the code and look at what was printed. Compare to expected results
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: Sorted list and compareTo method

    Aight I'll try that, thanks!

  4. #4
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: Sorted list and compareTo method

    Okay, so after trying for 2 days straight I'm quite lost in this program.I cannot get it to work and I need some assistance. I put comments on parts of the code that I'm not sure how to implement and what the idea behind the code is.

     
    class PhoneBookList implements PhoneBook {
    	private int size = 0;
    	Node head = null;
     
    	private static final class Node {
    		final Person person;
    		Node next;
     
    		Node(Person person) {
    			this.person = person;
    		}
    	}
     
    	public Person lookup(String name) {
    		Node p = head, prev = null;
     
    		while(p!=null) {
    		//Not really sure how to implement this method, idea is to compare the first element p with an string that the user puts in.
    			int comparison = p.compareTo(name);
     
    		  if(comparison == 0){
    			return //Not sure what my return value is,it is susposed to be a person with the correspoding name,how do I execute that?
    		  }
    		    else if(comparison != 0) {
    		      prev = p;
    			  p = p.next;
    			}
    		   //Idea behind this is to keep moving on in the list,if the first element isnt the one we looked for.
    		     else {
    				 return null;
    				 //If nothing found return null
    		      }
     
    	public boolean insert(Person person) {
    		 Node p = head, prev = null;
     
    		 while(p!=null) {
    		   int comparison = p.compareTo(person);
     
    		   if(comparison != 0) {
    			   return true;
    			   size++;
    		   }
    		   //This person doesnt exist, return true and increase the size by one.
    		  else  if(comparison == 0) {
    		      prev = p;
    		      p = p.next;
    		  }
     
    			  //The same idea as with lookup, maybe it isn't the first element keep looking.
    			  else {
    				  return false;
    				//Nothing found,return false.
    		 }
     
    		 Node n = new Node(person);
     
    		 if (prev == null){
    			 head = n;
    		 }else{ 
    		    prev.next = n;
                n.next = p;
    		 }
     
     }
    	public boolean delete(String name) {
    		Node p = head, prev = null; 
     
    		while(!p=null) {
    			int comparison = p.compareTo(name);
     
    			if(comparison == 0) {
    				return true;
    				size--;
    			}
    			//This person exists,we found it and we are going to delete it.
    			  else if(comparison != 0) {
    			   prev = p;
    		       p = p.next;
    			}
     
    			  else {
    				  return false;
    			  }
     
    		     if (prev == null) {
    				 head = p.next; 
    			} 
    			  else {
    				  prev.next = p.next;
    			}
    		}
    	}

    Maybe some help? An example on how to implement one of these methods or some guidance would be really nice! Thanks.

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Sorted list and compareTo method

    idea is to compare the first element p with an string
    This code is trying to compare the contents of two different types of objects: Node and String
    			int comparison = p.compareTo(name);
    I think the description of that code should be: compare the name of the person in the Node object with the string entered by the user.

    Change the code so that the comparison is between two objects of the same type.
    Does Node contain a name String that you want to compare against the variable: name? Then use p.getName() instead of p so that the code compares two Strings.


    Are there any error messages? Please copy the full text and paste it here.
    If you don't understand my answer, don't ignore it, ask a question.

  6. #6
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: Sorted list and compareTo method

    "I think the description of that code should be: compare the name of the person in the Node object with the string entered by the user."

    Yes that is exactly what i want the compare to method to do. How would I implement that, we haven't covered this compareTo method in class so I'm kinda going of my intuition per say.PhoneBookList.java:23: error: illegal start of expression
    }
    ^
    PhoneBookList.java:34: error: illegal start of expression
    public boolean insert(Person person) {
    ^
    PhoneBookList.java:66: error: illegal start of expression
    public boolean delete(String name) {
    ^
    3 errors

    These are the errors I am getting when i add the last method, which just to print out the size of the phone book.

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Sorted list and compareTo method

    haven't covered this compareTo method in class
    Look at the documentation for that method in the API doc: https://docs.oracle.com/javase/8/docs/api/index.html
    At the top of the page in the blue strip, click on the INDEX link. Then click on the C (first letter of method name)
    then do a Find for compareTo to see all the classes that the method is used in.
    Each class has its own compareTo method because only the class would know how to compare two instances of the class.

    PhoneBookList.java:23: error: illegal start of expression
    }
    Check that that {}s are properly paired. Each { needs a }
    If you don't understand my answer, don't ignore it, ask a question.

  8. #8
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: Sorted list and compareTo method

    Aight I'll do that

    --- Update ---

    Okay after some trying I've decided to take the program step by step, in order to make it easier.The logical way implies to start with the method insert and I've ran into an issue here. The method is boolean so it needs to return values true or false. In which part of the code do I return the values. After what checks?

     
    class PhoneBookList implements PhoneBook {
    	private int size = 0;
    	Node head = null;
     
    	private static final class Node {
    		final Person person;
    		Node next;
     
    		Node(Person person) {
    			this.person = person;
    		}
    	}
     
    	public boolean insert(Person person) {
    		Node p = head, prev = null; 
     
    		while(p!=null) {
    			int comparison = person.compareTo(person);
     
    		  if(comparison != 0) {
    			return true;
    			size++;
    		 }
    		    if(comparison == 0) {
    			prev = p;
                p = p.next;
    		  }
    	  }
     
    	Node n = new Node(person);
    	  if (prev == null){
    		  head = n;
    	  }
          else{
    		  prev.next = n;
              n.next = p;
    	  }
    	}
    }
    Now I think the part where you need to return the true value is quite obvious. After checking that the person doesn't exist return true and increase the size by 1. But where should I implement the return false method? Thanks.

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Sorted list and compareTo method

    After checking that the person doesn't exist return true
    Does that mean if the insert tries to add an existing entry, the code should return false?

    After what checks?
    What is insert supposed to do? Why does it exit if the compare returns not equal?

    There could be a boolean variable: valueToReturn that is set with the value to return when it is determined.
    When the code finishes processing it could execute: return valueToReturn;

    This code should cause a compiler error:
    		return true;
    		size++;    //<<<<<<No way to execute this statement

    This code is comparing a variable to itself - it should always be equal
       int comparison = person.compareTo(person);
    If you don't understand my answer, don't ignore it, ask a question.

  10. #10
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: Sorted list and compareTo method

    Yes if the entry that we are trying to insert alredy exists the code should return false.Insert is susposed to create a new Person object(insert it in the list). The person contains a name,adress and phone number. On the part with that valuetoReturn. Can you show me an example of what you mean? Maybe just a super short and basic code (few lines) so that I can visualise the concept. Thanks buddy!

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Sorted list and compareTo method

    an example of what you mean
    boolean returnVal = true; // set initial value
    // here is some code that does some tests
    // if you want to return false, set returnVal = false;
    // when exiting the method: return returnVal; // return what the method determined

    Is this what the insert method is supposed to do?
    Search the whole list to see if it already contains a matching entry
    If it does, return false.
    If it does not, add the new node at the end and return true.
    If you don't understand my answer, don't ignore it, ask a question.

  12. #12
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: Sorted list and compareTo method

    Hmmm okay gimme a few minutes to try to implement that.

    --- Update ---

    Aight I've implemented your suggestion like this;

     
    class PhoneBookList implements PhoneBook {
    	private int size = 0;
    	Node head = null;
     
    	private static final class Node {
    		final Person person;
    		Node next;
     
    		Node(Person person) {
    			this.person = person;
    		}
    	}
     
    	public boolean insert(Person person) {
    		Node p = head, prev = null; 
    		boolean value = true;
     
    		while(p!=null) {
    			int comparison = person.name.compareTo(person.name);
     
    		  if(comparison != 0) {
    			size++;
    		 }
    		    if(comparison == 0) {
    			prev = p;
                p = p.next;
    		    value = false;
    		  }
    	  }
     
    	Node n = new Node(person);
    	  if (prev == null){
    		  head = n;
    	  }
          else{
    		  prev.next = n;
              n.next = p;
    	  }
    	  return value;
    	}
    }

    The only error I'm getting is that I have not implemented all of the methods from the interface PhoneBook, which is true,sooo it should be working?

  13. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Sorted list and compareTo method

    Is there any more processing to be done in the method AFTER value is set to false?
    If there is nothing more the method should do, it could immediately return false and not execute any more code in the method.

    error I'm getting is that I have not implemented all of the methods from the interface
    Write empty methods for those and do some testing with the current code. Do not write any more code until the current code is working properly.

    This statement is comparing a variable (person.name) to itself >> will always be equal
    int comparison = person.name.compareTo(person.name);
    Should one of those variables use the Person inside of the Node?
    If you don't understand my answer, don't ignore it, ask a question.

  14. #14
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: Sorted list and compareTo method

    Well in the method insert no; That is if I've done everything and that includes; checking if a person with that name exists, if yes inserting that person if not returning false. And What do you mean empty methods. How does that look like?

    --- Update ---

    Yes I've ajusted that, I've realised that as well

  15. #15
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Sorted list and compareTo method

    An empty method would not contain any processing code. At a minimum it could have a return statement that returned a value of the required type. No return needed for void.
    For int: return 0;
    for boolean: return true;
    for a class: return null;
    If you don't understand my answer, don't ignore it, ask a question.

  16. #16
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: Sorted list and compareTo method

    PhoneBookList.java:19: error: cannot find symbol
    int comparison = p.name.compareTo(person.name);
    ^
    symbol: variable name
    location: variable p of type Node
    1 error

    This is the error I'm getting.

  17. #17
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Sorted list and compareTo method

    symbol: variable name
    location: variable p of type Node
    The compiler can not find a declaration for name in the class Node.
    Where is the variable name defined? Is it in the Person class object inside of Node?


    Note: p is a confusing name for a Node object. Can you use a more descriptive name?
    If you don't understand my answer, don't ignore it, ask a question.

  18. #18
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: Sorted list and compareTo method

    The variable name is defined in an class Person. Sure i'll use something a bit more descriptive.

  19. #19
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Sorted list and compareTo method

    The variable name is defined in an class Person
    Yes, not in the Node class. p.name does not exist.
    If you don't understand my answer, don't ignore it, ask a question.

  20. #20
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: Sorted list and compareTo method

    So how would I use this method to tell it compare the person in the list with the one the user inputs?

  21. #21
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Sorted list and compareTo method

    The name is in the Person object and that is inside of a Node object. Something like this:
    nodeRef.personRef.name

    The user's passed name is in a Person object: public boolean insert(Person person) {
    Use this to refer to that variable:
    personRef.name

    Compare those two values
    If you don't understand my answer, don't ignore it, ask a question.

  22. #22
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: Sorted list and compareTo method

    Hmmmm okay I'll give that a shot

    --- Update ---

    Okay so I've come up with something

     
    class PhoneBookList implements PhoneBook {
    	private int size = 0;
    	Node head;
     
    	private static final class Node { 
    		final Person person;
    		Node next;
     
    		Node(Person person) {
    			this.person = person;
    		}
    	}
     
    	public boolean insert(Person person) {
    		Node n = new Node(person); //die Person die sagen wir vor der Tür steht.
    		Node p = head,prev = null;// den Head auf p zuweisen.
     
     
    		if(p == null) {//Niemand ist in dem raum
    		    head = n;//also soll die neu Person die erste sein die rein geht.
    			return true;
    		}
     
    		int comparison = p.name.compareTo(n.name);//den Namen von der ersten person mit dem Namen der neuen person vergleichen.
     
    		if(comparison < 0) {
    			n.next = p;
    			p = n;
    			size++;// den wert size um 1 zu erhohen, brauche ich dass überhaupt?
    			return true;
    		}
     
    		if(comparison == 0) {
    			return false;
     
    		}
     
    		Node current = p;
    		while(current.next !=null && current.next.person < person) {
    			current = current.next;
    		}
    		if(current.next !=null && current.next.person == person) {
    			return false;
     
    		}
     
    		n.next = current.next;
            current.next = n;
            return true;
    	}


    Only thing left is to correctly implement the compareTo method. I will try what you suggested (ignore the comments its in german) but I think I've implemented all of the other parts of the method

  23. #23
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Sorted list and compareTo method

    p.name.compareTo(n.name)
    Does that compile? Does Node have a member named name? The code shows the only members of Node are a Person and a Node.

    current.next.person == person
    The == operator tests if the two object references point to the same object. It does not check the contents of the objects for equality.
    I assume you want to test the contents of the two objects. To do that you need a method, perhaps a compareTo method in the Person class.
    If you don't understand my answer, don't ignore it, ask a question.

  24. #24
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: Sorted list and compareTo method

    Is there a way to implement that method without chaning the Person class?

  25. #25
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Sorted list and compareTo method

    No. You need to change a class to add a method to it.
    The String class's compareTo method can be used to compare the name variables from two different instances of Node class/Person class. Your earlier code tried to do that. It just needed a small fix.
    If you don't understand my answer, don't ignore it, ask a question.

Page 1 of 2 12 LastLast

Similar Threads

  1. What does compareTo method of String do ?
    By djl1990 in forum Java Theory & Questions
    Replies: 5
    Last Post: December 18th, 2012, 03:39 AM
  2. Implementing the compareTo method?
    By colerelm in forum Java Theory & Questions
    Replies: 2
    Last Post: December 3rd, 2011, 07:47 PM
  3. Java Newbie - Sorted Linked List not inserting properly - please help!
    By bubbleboy in forum What's Wrong With My Code?
    Replies: 20
    Last Post: June 17th, 2011, 11:48 AM
  4. Replies: 3
    Last Post: June 1st, 2011, 12:47 AM
  5. Sorted Doubly linked List
    By student in forum What's Wrong With My Code?
    Replies: 2
    Last Post: October 15th, 2010, 09:52 PM