Results 1 to 4 of 4
  1. #1
    Adomini is offline Member
    Join Date
    Aug 2010
    Posts
    70
    Rep Power
    0

    Default Comparing Strings

    Hello all. I am still stuck on this Comparator class I have built with comparing Strings. there are no syntax errors, but it does not run. Can someone tell me what is wrong with this?

    Java Code:
    
    
    import java.util.Comparator;
    
    public class VehicleColorComparator 
    implements Comparator<Vehicle>, java.io.Serializable 
    
      {
    	
    	// uses the inherited compare method for the colors
    public int compare (Vehicle o1, Vehicle o2) 
    {
    	
    	String Color1 = o1.color;
    	String Color2 = o2.color;
       
    	
    	
    	if(Color1.compareTo(Color2)==0)
    		return 0;
    	if(Color1.compareTo(Color2) > 0)
    		return 1;
    	else
    		return -1;   
    
    }
    }

  2. #2
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    String has a built in compareTo, so your compare method could just be
    Java Code:
    return Color1.compareTo(Color2);

  3. #3
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,642
    Rep Power
    7

    Default

    but it does not run
    Define "does not run". Do you get exceptions? Does it sort when you try to use the comparator, for example sort using Collections.sort?

  4. #4
    Adomini is offline Member
    Join Date
    Aug 2010
    Posts
    70
    Rep Power
    0

    Default

    Sorry for the confusion. I was trying to use the compareTo method the strings already have, but the homework I was using was giving me fits. I think I got it, so I will solve this thread and post back if I have a problem in a few hours.

    Thanks all and sorry for the confusion once again.

Similar Threads

  1. comparing 3 strings with equalsignorecase
    By vividcooper in forum New To Java
    Replies: 4
    Last Post: 01-13-2010, 09:30 PM
  2. need in help in comparing Strings
    By jaq in forum New To Java
    Replies: 1
    Last Post: 11-25-2009, 01:06 PM
  3. comparing strings
    By diggitydoggz in forum New To Java
    Replies: 7
    Last Post: 12-23-2008, 04:40 AM
  4. Comparing Strings
    By souFrag in forum Advanced Java
    Replies: 5
    Last Post: 05-21-2008, 09:03 AM
  5. Comparing Strings
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 12-03-2007, 09:44 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •