Results 1 to 3 of 3
  1. #1
    Join Date
    Jul 2010
    Posts
    6
    Rep Power
    0

    Default how to use comparator

    I'm trying to give the user the option to display a list of prices in two different formats, by name and by price.

    It will sort it by name fine but it isn't sorting it by price. how do I get this darn thing to work? I can't seem to pinpoint what it is that isn't working. I haven't worked with comparators


    Java Code:
    import java.util.Comparator;
    import javax.swing.*;
    import java.util.*;
    import java.text.*;
    import java.util.Arrays;
    
    public class CoffeeDriver
    {
    	public static void main(String[] args)
       {
       	char choice;
          Item inventory[] = new Item[5]; 
          
    		inventory[0] = new Item("Coffee", 1.00); 
    		inventory[1] = new Item("Water", 2.00);
    		inventory[2] = new Item("Milk", 1.50);
    		inventory[3] = new Item("Bagel", 1.25);
    		inventory[4] = new Item("Donut", 0.75);
    		
    
    		choice = JOptionPane.showInputDialog(null,
    			"Welcome to Wings Coffee Shop." +
    			"\nWould you like to see these items sorted by" +
    			"\nname or by price? (n/p)", "n or p",
          JOptionPane.QUESTION_MESSAGE).charAt(0);
          choice = Character.toLowerCase(choice);                          
                           
    		switch(choice)
          {
          	case 'n':  
                Arrays.sort(inventory);
    				System.out.println();
        			System.out.println("By name:");
    
         			for (int i=0; i<4; i++)
    				{
          			Item item = inventory[i];
         				String name = item.getName();
          			double price = item.getPrice();
          			System.out.println(name + "    " + price);
        			} 	
    				break;
             
    			case 'p':
    				Arrays.sort(inventory);
    				System.out.println();
        			System.out.println("By price:");
    
        			for (int i=0; i<4; i++) 
    	 			{
          			Item item = inventory[i];
          			String name = item.getName();
          			double price = item.getPrice();
          			System.out.println(name + "    " + price);
        			}
                break;
             
    			default:
                JOptionPane.showMessageDialog(null,
    				"Invalid entry, Please try again");
                break;
           }         
     	 }
    }

    Java Code:
    import java.util.Comparator;
    
    public class Item implements Comparable<Item>
    {
    	String name;
       double price = 0.00;
       
    	// Constructor
    	public Item(String itemName, double itemPrice)
    	{
    		this.name = itemName;
          this.price = itemPrice;
       }
    	// Set name method
    	public void setName(String name)
    	{
       	this.name = name;
    	}
    	// Get name  method
    	public String getName()
    	{
       	return name;
    	}
    	// Get price method
       public void setPrice(double price)
       {
       	this.price = price;
       }	  
    	// Set price method	  
    	public double getPrice()
       {
       	return price;
       }
     	//compare items by name:
      	public int compareTo(Item otherName) 
    	{
    		
        return name.compareTo(otherName.getName());
       }
    }

    Java Code:
    package comparable.ex03;
    import java.util.Comparator;
    
    public class NameComparator<Item> implements Comparator<Item>
    {
    	public int compare(Item o1, Item o2)
    	{
    		String itemName1 = o1.getName();
    		String itemName2 = o2.getName();
    		return itemName1.compareTo(itemName2);
    	}
    }
    Java Code:
    package comparable.ex03;
    import java.util.Comparator;
    
    public class PriceComparator<Item> implements Comparator<Item>
    {
    	public int compare(Item o1, Item o2)
    	{
    		return o1.getPrice().compareTo(o2.getPrice());
        }
    	
    	//	int itemPrice1 =  o1.getPrice();
       //   int itemPrice2 =  o2.getPrice();
                    
         // if(itemPrice1 > itemPrice2)
    	//{
       //   	return 1;
         //}
          //  else if(itemPrice1 < itemPrice2)
    	//{
       //     return -1;
        // }
         //  else return 0;
    	//}
    }

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    The sort is based on the compareTo method. If you want to sort based on price then use the prices of the current object vs the other object determine what is returned by compareTo. If the price of the current object is greater than the other, than return 1, if current is less, return -1, if the same, return 0.

  3. #3
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,447
    Blog Entries
    7
    Rep Power
    20

    Default

    Two fragments of code; this one:

    Java Code:
    Arrays.sort(inventory);
    System.out.println();
    System.out.println("By name:");
    and this one:

    Java Code:
    Arrays.sort(inventory);
    System.out.println();
    System.out.println("By price:");
    The Arrays.sort( ... ) method isn't psychic, it either sorts an array of Comparables (i.e. objects that implement the Comparable interface) or it uses an implementation of the Comparator interface. You have (partially?) implemented such an interface so you should use it in the second sort call because your Comparable implementation compares by name, the Comparator interface compares by price.

    kind regards,

    Jos

Similar Threads

  1. Replies: 6
    Last Post: 02-20-2009, 10:03 AM
  2. Use different comparator for SortedSet
    By linus_k in forum New To Java
    Replies: 0
    Last Post: 11-21-2008, 02:46 PM
  3. How to search with a Comparator
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-15-2008, 07:39 PM
  4. How to write your own Comparator
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-15-2008, 07:38 PM
  5. Using Comparable and Comparator interfaces
    By barney in forum New To Java
    Replies: 1
    Last Post: 08-07-2007, 07:10 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
  •