Results 1 to 9 of 9
  1. #1
    kbullard516 is offline Member
    Join Date
    Feb 2009
    Posts
    9
    Rep Power
    0

    Default [SOLVED] Sorting / compareTo method confusion. Please help

    Hello. My task is import data from a text file into an array, and then sort the array and print out the sorted array. Each element of the array represents a clothing item and has name,category,quantity, and price values. I have an Item class to represent a single clothing item, a sorting class with multiple sorting methods, and a class to test the sort and print the array (with the main method). Category values are either "C","W", or "M" (child, women, or men), and i have to sort the array in the order of C, then W, then M. How can i edit my compareTo method to do so? since M comes before W, i do not know how to write my compareTo method to sort the items of category W before the ones of category M.

    the data file looks as follows: (if theres a better way to type this out here on these forums, please let me know)

    Suit C 12 12.99
    Shirt C 25 12.99
    Blazer W 16 45.79
    Suit M 12 299.00
    Suit W 17 127.99
    Suit C 12 12.99
    Pants W 33 54.99
    Pants C 22 10.59
    Pants M 12 10.59
    Skirt W 17 39.99
    Sweater C 25 10.27
    Sweater W 17 47.99


    heres the code that i have so far:

    Java Code:
    /**
     * Class ItemTester
     * Creates and prints an array of items
     * Asks user to choose how to sort array
     * Prints sorted array of items
     */
    import java.util.Scanner;
    import java.io.*;
    
    public class ItemTester
    {
       public static void main(String[] args) throws IOException
       {     
          String line;
          Scanner scanToken;  
          Scanner scan = new Scanner(new File("Indata.txt"));
          Item[] itemList = new Item[12];
          String name;
          String category;
          int quantity;
          double price;
          int size = 0;
          while (scan.hasNext())
          {
             line = scan.nextLine();
             scanToken = new Scanner(line);
             scanToken.useDelimiter(" ");            
             name = scanToken.next();
             category = scanToken.next();
             quantity = scanToken.nextInt();
             price = scanToken.nextDouble();
             itemList[size] = new Item(name,category,quantity,price);
             size++;      
          }
          System.out.println("Printout of the array");
          System.out.println();
          System.out.println("Name         Category         Quantity           Price");
          System.out.println();
          for ( int i = 0; i < size; i++)
          {
             System.out.println(itemList[i] + "\t"); 
          }
          System.out.println();  
          System.out.print("Array has " + size + " items");
    
          System.out.println();
          System.out.println();
          System.out.println();
          System.out.println();
    
          Sorting.selectionSort(itemList);
    
          for ( int i = 0; i < size; i++)
          {
             System.out.println(itemList[i] + "\t"); 
          }
        }
    }
    
    
    /**
     * Class Item
     * Represents A Single Item
     */
    
    import java.text.NumberFormat;
    
    public class Item implements Comparable
    {
        // instance variables
        public String name;
        public String category;
        public int quantity;
        public double price;
    
        /**
         * Constructor for objects of class Item
         */
        public Item(String n, String c, int q, double p)
        {
            // initialise instance variables
            name = n;
            category = c;
            quantity = q;
            price = p;
        }
    
        /**
         * 
         * Methods of class Item
         */
        
       public String toString()
       {    
          NumberFormat fmt =NumberFormat.getCurrencyInstance();
          return name + "\t\t" + category + "\t\t" + quantity + "\t\t" + fmt.format(price); 
       }
       
       public String getName()
       {
           return name;
       }
       
       public String getCategory()
       {
           return category;
       }
       
       public int getQuantity()
       {
           return quantity;
       }
       
       public double getPrice()
       {
           return price;
       }
       
       public int compareTo(Object other)
       {
           int result;
           
           String otherName = ((Item)other).getName();
           String otherCategory = ((Item)other).getCategory();
           int otherQuantity = ((Item)other).getQuantity();
           double otherPrice = ((Item)other).getPrice();
           
           if (category.equals(otherCategory))
                result = name.compareTo(otherName);
           else
                result = category.compareTo(otherCategory);
    
           
                
           return result;
           
       }
           
           
    
    }
    
    
    /**
     * Class Sorting
     * Contains 3 different sort methods
     */
    public class Sorting
    {
       public static void selectionSort (Comparable[] iArray)
       {
           int min;
           Comparable temp;
           
           for (int index = 0; index < iArray.length-1; index++)
           {
               min = index;
               for (int scan = index+1; scan < iArray.length; scan++)
                  if (iArray[scan].compareTo(iArray[min]) < 0)
                     min = scan;
                     
              // Swap the values
              temp = iArray[min];
              iArray[min] = iArray[index];
              iArray[index] = temp;
          }
       }
       
       
       public static void insertionSort (Comparable[] iArray)
       {
           for (int index = 1; index < iArray.length; index ++)
           {
               Comparable key = iArray[index];
               int position = index;
               
               // Shift larger values to the right
               while (position > 0 && key.compareTo(iArray[position-1]) < 0)
               {
                   iArray[position] = iArray[position -1];
                   position--;
               }
               
               iArray[position] = key;
            }
       }
    
    
    
       public static void bubbleSort(Comparable[] iArray)
       {
      
       boolean changed = false;
       for(int a = 0; a < iArray.length - 2; a++)
       {
          if(iArray[a].compareTo(iArray[a + 1]) > 0)
          {
             Comparable tmp = iArray[a];
             iArray[a] = iArray[a + 1];
             iArray[a + 1] = tmp;
             changed = true;
          }
       }
    
       }
    
    }

    If anyone could give me suggestions on how to revise my compareTo() method, it would be greatly appreciated. I need to design it in such a way that items are compared based on category first. (all C before W and all W before M). If two items are in the same category then they are based on quantity. If quantity is also the same, then items are compared based on their name.

    Thanks again for any help

  2. #2
    angryboy's Avatar
    angryboy is offline Senior Member
    Join Date
    Jan 2009
    Posts
    742
    Rep Power
    6

    Default

    suggestion: you can use enum types for category. then W can come before M.
    USE CODE TAGS--> [CODE]...[/CODE]
    Get NotePad++ (free)

  3. #3
    kbullard516 is offline Member
    Join Date
    Feb 2009
    Posts
    9
    Rep Power
    0

    Default

    How would i do that, would i just change the instance variable of category in class Item to public enum category {C,W,M}; ? because the modifier enum isnt allowed in the constructor, so im not sure how id have that enum value assigned to the object

  4. #4
    angryboy's Avatar
    angryboy is offline Senior Member
    Join Date
    Jan 2009
    Posts
    742
    Rep Power
    6

    Default

    you'd need a separate enum class call Category. then instead of using "String category;", you'd need to use: "Category category;". and everything that references category need to be of type Category.X.
    USE CODE TAGS--> [CODE]...[/CODE]
    Get NotePad++ (free)

  5. #5
    kbullard516 is offline Member
    Join Date
    Feb 2009
    Posts
    9
    Rep Power
    0

    Default

    Ok, i did what you told me to do, however i am now running into another problem. In my ItemTester i use a delimiter to separate the parts of the element (name, category, quantity, price) from each line of the text file and assign them to Item. i created an enum class Category and changed all the "String category"s to "Category category". however in my ItemTester, the line "category = scanToken.next();" is giving me an error. when i compile in BlueJ, it says "incompatible types - found java.lang.String but expected category". Im not sure how to fix that since there is no nextCategory() method.

    heres a code update:

    Java Code:
    public enum Category
    {
        C(1),W(2),M(3);
        int cate;
        
        Category(int cat) 
        {
        cate = cat;
        }
    }
    
    import java.text.NumberFormat;
    
    public class Item implements Comparable
    {
        // instance variables
        public String name;
        public Category category;
        public int quantity;
        public double price;
    
        /**
         * Constructor for objects of class Item
         */
        public Item(String n, Category c, int q, double p)
        {
            // initialise instance variables
            name = n;
            category = c;
            quantity = q;
            price = p;
        }
    
        /**
         * 
         * Methods of class Item
         */
        
       public String toString()
       {    
          NumberFormat fmt =NumberFormat.getCurrencyInstance();
          return name + "\t\t" + category + "\t\t" + quantity + "\t\t" + fmt.format(price); 
       }
       
       public String getName()
       {
           return name;
       }
       
       public Category getCategory()
       {
           return category;
       }
       
       public int getQuantity()
       {
           return quantity;
       }
       
       public double getPrice()
       {
           return price;
       }
       
       public int compareTo(Object other)
       {
           int result;
           
           String otherName = ((Item)other).getName();
           Category otherCategory = ((Item)other).getCategory();
           int otherQuantity = ((Item)other).getQuantity();
           double otherPrice = ((Item)other).getPrice();
           
           if (category.equals(otherCategory))
                result = name.compareTo(otherName);
           else
                result = category.compareTo(otherCategory);
                
           return result;
           
       }
           
           
    
    }
    
    public class Sorting
    {
       public static void selectionSort (Comparable[] iArray)
       {
           int min;
           Comparable temp;
           
           for (int index = 0; index < iArray.length-1; index++)
           {
               min = index;
               for (int scan = index+1; scan < iArray.length; scan++)
                  if (iArray[scan].compareTo(iArray[min]) < 0)
                     min = scan;
                     
              // Swap the values
              temp = iArray[min];
              iArray[min] = iArray[index];
              iArray[index] = temp;
          }
       }
       
       
       public static void insertionSort (Comparable[] iArray)
       {
           for (int index = 1; index < iArray.length; index ++)
           {
               Comparable key = iArray[index];
               int position = index;
               
               // Shift larger values to the right
               while (position > 0 && key.compareTo(iArray[position-1]) < 0)
               {
                   iArray[position] = iArray[position -1];
                   position--;
               }
               
               iArray[position] = key;
            }
       }
       
       public static void bubbleSort(Comparable[] iArray)
       {
      
       boolean changed = false;
       for(int a = 0; a < iArray.length - 2; a++)
       {
          if(iArray[a].compareTo(iArray[a + 1]) > 0)
          {
             Comparable tmp = iArray[a];
             iArray[a] = iArray[a + 1];
             iArray[a + 1] = tmp;
             changed = true;
          }
       }
    
       }
    
     
    
    
    }
    
    
    import java.util.Scanner;
    import java.io.*;
    
    public class ItemTester
    {
       public static void main(String[] args) throws IOException
       {     
          String line;
          Scanner scanToken;  
          Scanner scan = new Scanner(new File("Indata.txt"));
          Item[] itemList = new Item[12];
          String name;
          Category category;
          int quantity;
          double price;
          int size = 0;
          while (scan.hasNext())
          {
             line = scan.nextLine();
             scanToken = new Scanner(line);
             scanToken.useDelimiter(" ");            
             name = scanToken.next();
             category = scanToken.next();
             quantity = scanToken.nextInt();
             price = scanToken.nextDouble();
             itemList[size] = new Item(name,category,quantity,price);
             size++;      
          }
          System.out.println("Printout of the array");
          System.out.println();
          System.out.println("Name         Category         Quantity           Price");
          System.out.println();
          for ( int i = 0; i < size; i++)
          {
             System.out.println(itemList[i] + "\t"); 
          }
          System.out.println();  
          System.out.print("Array has " + size + " items");
    
          System.out.println();
          System.out.println();
          System.out.println();
          System.out.println();
        }
    }

  6. #6
    angryboy's Avatar
    angryboy is offline Senior Member
    Join Date
    Jan 2009
    Posts
    742
    Rep Power
    6

    Default

    then use an if-else statement.
    Java Code:
    String cat = scanToken.next();
    if (cat.equals("W")) category = Category.W;
    else if(...)...
    ...//and so on
    edit:
    you need to fix up compareTo method. that is not how you compare enum types.
    USE CODE TAGS--> [CODE]...[/CODE]
    Get NotePad++ (free)

  7. #7
    kbullard516 is offline Member
    Join Date
    Feb 2009
    Posts
    9
    Rep Power
    0

    Default

    Thanks Alot for the suggest of using an enum type! I finally got it to work.

  8. #8
    angryboy's Avatar
    angryboy is offline Senior Member
    Join Date
    Jan 2009
    Posts
    742
    Rep Power
    6

    Default

    you're welcome, and thanks for making this as solved. ;)
    USE CODE TAGS--> [CODE]...[/CODE]
    Get NotePad++ (free)

  9. #9
    angryboy's Avatar
    angryboy is offline Senior Member
    Join Date
    Jan 2009
    Posts
    742
    Rep Power
    6

    Default better use of enum types.

    this would be better so you don't need to use if-else statements. just use Cat.valueOf(char) method to get back an enum type.

    Java Code:
    enum Cat{
      CHILD('C'),
      WOMEN('W'),
      MEN('M'),
      ; // end enum type
    
    [B]  private static final Map<Character,Cat> _INDEX;
      static{
        _INDEX = new HashMap<Character,Cat>();
        for(Cat cat: Cat.values())
          _INDEX.put(cat.getCode(),cat);
      }[/B]
    
      private final char _CODE;
    
      private Cat(final char c){
        this._CODE = c;
      }
    
      public char getCode(){ return this._CODE; }
      
    [B]  public static Cat valueOf(final char key){
        return _INDEX.get(key);
      }[/B]
    
    }
    USE CODE TAGS--> [CODE]...[/CODE]
    Get NotePad++ (free)

Similar Threads

  1. [SOLVED] calling a boolean method, confusion!!
    By AngrYkIdzrUlE in forum New To Java
    Replies: 18
    Last Post: 03-15-2009, 11:23 AM
  2. how do i reverse this method for sorting?Again!
    By PureAwesomeness in forum New To Java
    Replies: 2
    Last Post: 03-09-2009, 01:51 AM
  3. [SOLVED] how do i reverse this method for sorting?
    By PureAwesomeness in forum New To Java
    Replies: 3
    Last Post: 03-08-2009, 10:37 PM
  4. compareTo()
    By Tsiliadoros in forum Advanced Java
    Replies: 5
    Last Post: 10-03-2008, 02:18 PM
  5. how compareTo Method works
    By nanaji in forum Advanced Java
    Replies: 1
    Last Post: 06-22-2008, 08:40 PM

Posting Permissions

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